WP_query and pagination?

The question:

I have to get some custom post types and need to do that with WP_Query (query_posts doesn’t work).

How can I do the pagination? Whatever I tried didn’t work… any help would be awesome I can’t crack this alone…

$args = array(
'tax_query' => array(
   'posts_per_page' => 5,
    array(
    'author' => $user_id,
        'taxonomy' => 'custom_taxtype',
        'field' => 'slug',
        'terms' => 'delicious-food',
    )
) 
); 
$answer_query = new WP_Query( $args );

//// Loop trough the results

while ( $answer_query->have_posts() ) : $answer_query->the_post();

//// do something

endwhile;

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

If you could tell us what you’re exactly trying to achieve, we can help you better!

<?php
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
               'post_type' => 'question',
               'posts_per_page' => -1,
               'paged' => $paged,
               'author' => $user_id
            );
$my_query = new WP_Query($args);

if($my_query->have_posts()):
    while($my_query->have_posts()):$my_query->the_post();
        //Loop goes here...
    endwhile;
    //support for page-navi plugin, please refer readme.txt for further instructions
    if ( function_exists('wp_pagenavi') )
    {
        wp_pagenavi();
    }
    elseif ( get_next_posts_link() || get_previous_posts_link() )
    {
        ?>
        <div class="wp-navigation clearfix">
            <div class="alignleft"><?php //next_posts_link('&laquo; Older Entries'); ?></div>
            <div class="alignright"><?php //previous_posts_link('Newer Entries &raquo;'); ?></div>
        </div>
<?php } //if wp_pagenavi
endif;
?>

Check WP_Query documentation for more parameters.

Btw, query_posts also works with custom posts, as it takes all the parameters that you can pass to WP_Query.

Method 2

IF you change the $my_query to $wp_query it should work. The code in the internal wordpress functions next_posts_link & previous_posts_link expect the query object to be called $wp_query.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment