• Resolved balistrerin

    (@balistrerin)


    So I know that WordPress has a lot of pagination functions but they only seem to work with posts. On the users my-account page of woocommerce there is a section for “Available Downloads”. I sell digital downloads and some customers have so many of these digital downloads that they either can’t load their my-account page anymore or it takes a very long time to load. I was hoping that there was some simple way to add pagination to this section but I can’t find anything out there. I have tried several options. In woocommerce there is a PHP file called my-downloads.php and it accesses a users downloads in an array via:

    $downloads = WC()->customer->get_downloadable_products()

    Inside the file then it loops through the array and displays their download link.

    `<ul class=”digital-downloads”
    <?php foreach ( $downloads as $download ) :
    <li>?php echo apply_filters( ‘woocommerce_available_download_link’, ‘<a href=”‘ . esc_url( $download[‘download_url’] ) . ‘”> class=”fa fa1 fa-download”‘ . $download[‘product_name’] . ‘</a>’, $download );</li>
    </ul>`

    How Can I add pagination to this page successfully within this foreach loop?

    I have tried adding this after the $downloads array is initialized

    `$page = ! empty( $_GET[‘page’] ) ? (int) $_GET[‘page’] : 1;
    $total = count( $downloads ); //total items in array
    $limit = 5; //per page
    $totalPages = ceil( $total/ $limit ); //calculate total pages
    $page = max($page, 1); //get 1 page when $_GET[‘page’] <= 0
    $page = min($page, $totalPages); //get last page when $_GET[‘page’] >
    $totalPages
    $offset = ($page – 1) * $limit;
    if( $offset < 0 ) $offset = 0;

    $downloads = array_slice( $downloads, $offset, $limit );`

    I then tried to add the pagination links down at the bottom of the file:

    `$link = ‘/my-account/?page=%d’;
    $pagerContainer = ‘<div style=”width: 300px;”>’;
    if( $totalPages != 0 )
    {
    if( $page == 1 )
    {
    $pagerContainer .= ”;
    }
    else
    {
    $pagerContainer .= sprintf( ‘<a href=”‘ . $link . ‘”> « prev page</a>’, $page – 1 );
    }
    $pagerContainer .= ‘ <span> page <strong>’ . $page . ‘</strong> from ‘ . $totalPages . ‘</span>’;
    if( $page == $totalPages )
    {
    $pagerContainer .= ”;
    }
    else
    {
    $pagerContainer .= sprintf( ‘<a href=”‘ . $link . ‘”> next page » </a>’, $page + 1 );
    }
    }
    $pagerContainer .= ‘</div>’;

    echo $pagerContainer;`

    I feel like I am close but I can’t get it to work 100% the way that I want. Any help would be greatly appreciated.

    • This topic was modified 5 years, 9 months ago by balistrerin.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘How to paginate through digital downloads woocommerce PHP’ is closed to new replies.