Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Gary Stewart
Gary Stewart
14,142 Points

Add pagination to my WP_Query?

Hi, I'm getting lost in this and cannot get it to work hence resorting to asking for your kind help if you can.

I have a Query as below:

<?php
function myVotes($userID,$returnCount) {

$args = array (
    'post_type'              => 'vote',
    'posts_per_page'         => $returnCount,
    'meta_key'               => 'end_order_full_date',
    'orderby'                => 'meta_value_num',
    'order'                  => 'DESC',
    'meta_query'             => array(
        array(
            'key'       => 'status',
            'value'     => 'Completed'
        ),
        array(
            'key'       => 'voters_id',
            'value'     => $userID
        )
    ),
);

$query = new WP_Query( $args );

   return $query;
    wp_reset_postdata();
}

This successfully gets the information in the format I would like (I am passing a return count of 3 as I would like to show three posts with pagination underneath to reach the rest). And this code brings back the information I need but am not sure as to how to change/add to this code to get pagination working?

My loop is as follows:

 <?php
    $myVotes = myVotes($userID,3);


if ($myVotes->have_posts()) : while ($myVotes->have_posts()) : $myVotes->the_post();

        // CALL MY TITLES AND OTHER INFO TO DISPLAY ETC

endwhile; else :
        echo '<div id="error_main">';
        echo "You have not placed any votes.";
        echo '</div>';
endif; 



} else {
    wp_redirect( home_url() );
    exit;
}
?>

So as you have probably worked out, I have a custom page template using the above loop and am hoping to list just three post titles/other info with pagination underneath the three to show three more....etc.

Thanks in advance for your help!

2 Answers

Gary Stewart
Gary Stewart
14,142 Points

Can anyone help!? Really struggling to get it working :(

I've only just started looking into something similar myself, I've found seeting "Blog pages show at most" in Settings > Reading and adding the type of pagination navigation you want which can be fouhd:

https://codex.wordpress.org/Pagination