I am trying to modify the number of posts per page for archive pages that contain category sticky posts (added by the Category Sticky post plugin)

to do so I am using the pre_get_postshook and have tried the following :

add_action( 'pre_get_posts', 'my_set_category_posts_per_page' );

function my_set_category_posts_per_page( $query ) {

  global $wp_the_query;

  if ( 'category_sticky_post' === $query->get( 'meta_key' ) && ! is_paged ) {

        $query->set( 'posts_per_page', 8 );


  return $query;

I var_dump($query) I do get [meta_key] => category_sticky_post in the query_vars but I can't sort out how to use it.

Another idea is to use something like this:

function my_set_category_posts_per_page( $query ) {

  $args = array(
            'key'     => 'category_sticky_post',
            'compare' => 'EXISTS'
    $meta_query = new WP_Meta_Query($args);

    if ( 'category_sticky_post' === $query->get('meta_query', $meta_query) && ! is_paged() ) {

       $query->set( 'posts_per_page', 8 );


How would I alter the query only when the meta key is present for the posts in the current query?

  • 1
    Is the key/value [meta_key] => category_sticky_post nested under query_vars in the $query object? I think your condition should look more like 'category_sticky_post' === $query->query_vars['meta_key'] – jdm2112 Oct 18 '16 at 18:26
  • it is indeed. Thanks, I'll have to wait until tomorrow to test it. I think I did try that but I'm not sure now. It looks like it should work. – mantis Oct 18 '16 at 19:41
  • So when I var_dump($query->query_vars['meta_key']) I do get category_sticky_postbut however the condition doesn't return true. – mantis Oct 19 '16 at 8:09
  • How about posting a dump of the entire $query object to Gist or Pastebin, etc? Can't guarantee a solution but I'm happy to take a deeper look. – jdm2112 Oct 19 '16 at 14:20
  • That would be great. I would love another pair of eyes on it. I'll do that tomorrow. Thanks :) – mantis Oct 19 '16 at 20:04

Based on data from your Gist, the following pre_get_posts condition should work to limit your posts per page.

add_action( 'pre_get_posts', 'my_set_category_posts_per_page' );

function my_set_category_posts_per_page() {
    global $wp_query;

    if ( 'category_sticky_post' === $wp_query->query_vars['meta_key'] ) {
      $wp_query->set( 'posts_per_page', 8 );
  • Thanks so much. I won't have a chance to try it out until tomorrow but looks promising ;) – mantis Oct 20 '16 at 17:58
  • Afraid it work. I think it has to use $wp_the_query and pass in $queryas a parameter. At least that's how I have it working elsewhere. Cheers for trying :) – mantis Oct 21 '16 at 14:24
  • nevermind that last comment. Turns out they are the same thing. – mantis Oct 21 '16 at 14:34

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.