modifying meta_query on parse_query

Right after the pre_get_posts hook is fired, the public meta_query attribute of WP_Query is overridden with:

$this->meta_query = new WP_Meta_Query(); 
$this->meta_query->parse_query_vars( $q );

where

$q = &$this->query_vars;
$q = $this->fill_query_vars($q);

So I don’t think it will work to modify this attribute, like you’re trying to do, before the pre_get_posts hook is activated.

Instead we need to pass the meta_query arguments through the query_vars part of the WP_Query.

So try for example this instead:

if ( ! $query->get( 'meta_query' ) ) {
    $query->set( 'meta_query', [
        [
            'key'     => 'ysr_home_sticky',
            'value'   => '1',
            'compare' => '='
        ]
    ] );
}

Leave a Comment