0

I can´t get works fine the pagination in archives for wordpress when i want limite the posts by page , if i let pagination by default as 10 from backend i haven´t problems but if i use this no works

$wp_query->posts_per_page = 5;
if ( have_posts() ) : while ( have_posts() ) : the_post();

For example in other pages i can limit the posts by page without problems but in archive always have problems for paginate , or give errors 404 in some pages or paginate bad , etc

Thank´s

2

You should not be setting the posts_per_page value in the template, nor should you be setting the object property directly after the query has run. That is going to cause the object data to become out of sync with itself.

You need to alter that value with a filter on pre_get_posts.

function pregp_archive_ppp_wpse_108225($qry) {
  if ($qry->is_main_query() && $qry->is_archive()) {
      $qry->set('posts_per_page',5);
  }
}
add_action('pre_get_posts','pregp_archive_ppp_wpse_108225');

The precise conditions you need may be different from the above example. You may need, for example, is_page_template() instead of is_archive().

2
  • And with my example how i can fix for works because i want use this in the archive template page – Fran Jul 29 '13 at 15:57
  • Did I not just answer that question? – s_ha_dum Jul 29 '13 at 16:16
0

Method 1: You can use pre_get_posts in your functions file to alter the query. This would go in your theme's functions.php file.

function limit_archive_posts( $query ) {
if ( $query->is_archive() && $query->is_main_query() && !is_admin() ) {
        $query->set( 'posts_per_page', 5);
    }
}
add_action( 'pre_get_posts', 'limit_archive_posts' );

Method 2: This can also be achieved by placing the following code before the loop in the archive page.

global $query_string;
query_posts("{$query_string}&posts_per_page=5");

If you have used with custom post type like 'news' then you can use below code for that.You can use pre_get_posts in your functions file to alter the query. This would go in your theme's functions.php file.

function limit_news_archive_post_type( $query ){
    if($query->is_post_type_archive('news') && $query->is_main_query() && !is_admin()){
            $query->set( 'posts_per_page', 5 );
    }
}
add_action( 'pre_get_posts', 'limit_news_archive_post_type' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.