I have a widget in the sidebar that shows recent posts. The code below works to set the number of posts per page in each category, but it also affects the sidebar. Is there any way to exclude the sidebar?

/** Different number of posts per page depending on the category **/
function hwl_home_pagesize( $query ) 
    if ( is_category( 'video' ) )
    // If you want "showposts"
    $query->query_vars['showposts'] = 10;
add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );  

2 Answers 2


Check for is_main_query on the query object.

if ( is_category( 'video' ) && $query->is_main_query() )

You should always do the two following checks

  • Check that your current query is the main query

  • Check that the query is a front end query

pre_get_posts alters all instances of WP_query, front end and back end, so you will need to make double sure you are doing the above checks

Also is_category() should be an object of $query

Your conditional should look like this

if( !is_admin() && $query->is_main_query() && $query->is_category() ) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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