12

In the wordpress settings => Reading => Blog pages show at most [input field] posts

I have it set to 3 posts at the moment.

On my index, date archives, tag archives, category archives, search results, etc... All pages that use the loop and paging, it shows 3 posts per page now.

My goal is to be able to have different number of results for different pages. ON my index maybe have 3 posts but on search results or archives, show a different number of results per page.

Any ideas how to do this?

20

This will do it: (add to your theme's functions.php)

add_action( 'pre_get_posts',  'set_posts_per_page'  );
function set_posts_per_page( $query ) {

  global $wp_the_query;

  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
    $query->set( 'posts_per_page', 3 );
  }
  elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
    $query->set( 'posts_per_page', 5 );
  }
  // Etc..

  return $query;
}
  • Is set a method of $query? – Rutwick Gangurde Oct 11 '11 at 4:34
  • @RutwickGangurde Yes. In fact, is_search() and is_archive() are too, which is now a little more clear after updating my answer with info gleaned from this great post: billerickson.net/customize-the-wordpress-query That article also notes that we'll have the $wp_query->is_main_query() method in WP3.3, which is pretty cool. – Dave Romsey Oct 11 '11 at 5:10
  • Awesome man! Thanks a lot for the great post. I never knew these methods, and I used to drill down the object / array to change / set values. Good for on the fly hacks! +1 for you! – Rutwick Gangurde Oct 11 '11 at 5:20
  • Since when was it necessary to never change it if is_admin dashboard? Looks like it doesn't sync the "Number of items per page:" in screen options in WP possibly resulting in pages you can't page to. – NoBugs Jan 18 '16 at 23:03
0

Improving on the answer above: hook pre_get_posts is fetched by reference, thus it does not require a global call or a returncall.

add_action( 'pre_get_posts',  'set_posts_per_page'  );
function set_posts_per_page( $query ) {

  if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
    $query->set( 'posts_per_page', 3 );
  }
  elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
    $query->set( 'posts_per_page', 5 );
  }
  // Etc..

}

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.