Alter query using pre_get_posts() if meta_key is present

Question

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(
        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?

0
, mantis 5 years 2016-10-18T07:56:57-05:00 0 Answers 71 views 0

Leave an answer

Browse
Browse