JoolsyM
JoolsyM

Reputation: 23

Pagination not working with WP_query

I'm trying to list the posts from the category 'alps'. The problem is if I define 'posts_per_page'=> -1, that works fine and I get the complete list, but if I ask for a number of posts I just get the same posts repeating page after page. Here's my loop-alps.php file.

<?php
$args = array(

'order' => 'asc',
'order_by' => 'title',
'posts_per_page'=> 5, 
'category_name'=> 'alps'
);

$wp_query = new WP_Query($args);

if($wp_query->have_posts()): while($wp_query->have_posts()): $wp_query->the_post();
echo '<h1>' .get_the_title() .'</h1>';
the_post_thumbnail();
endwhile;

endif;
?>



<div class="navigation">
<?php if(function_exists('tw_pagination')) tw_pagination($the_query); ?>
</div>

Upvotes: 1

Views: 7909

Answers (3)

Asrofi Wahono
Asrofi Wahono

Reputation: 1

Just add 'paged' => get_query_var( 'paged' ), like this, adjust it to your own

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$myposts = array(
    'showposts' => 6,
    'post_type' => 'your-post-type',
    'orderby' => 'date',
    'paged' => get_query_var( 'paged' ),
    'tax_query' => array(
        array(
        'taxonomy' => 'your-taxonomy',
        'field' => 'slug',
        'terms' => 'your-terms')
    )
);
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query($myposts);
?>

Upvotes: -3

JoolsyM
JoolsyM

Reputation: 23

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(

'order' => 'asc',
'order_by' => 'title',
'posts_per_page' => 12,
'category_name' => 'alps',
'paged' => $paged,
'offset'=> 1
);

Upvotes: 1

Ofir Baruch
Ofir Baruch

Reputation: 10346

According to WP documentation (Codex) it seems that you should use the paged parameter in order to make it work correctly.

$args = array(

'order' => 'asc',
'order_by' => 'title',
'posts_per_page'=> 5, 
'category_name'=> 'alps',
'paged' => get_query_var( 'paged' )
);

get_query_var( 'paged' ) - this function basically look for a GET variable in the URL, '?paged=X' if i'm not mistake. So make sure that by clicking on the pagination links you can see that this parameter is being added to the URL and is being changed accordingly.

Source: https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters

Upvotes: 4

Related Questions