In the parse_query
filter hook I’m doing:
if ( is_admin() && $pagenow == 'edit.php' && isset( $_GET['ysr_homepage_filter'] ) && $_GET['ysr_homepage_filter'] == '1' ) {
if ( ! $query->meta_query ) {
$query->meta_query = new WP_Meta_Query( [
[
'key' => 'ysr_home_sticky',
'value' => '1',
'compare' => '='
]
] );
}
}
to try to filter by a particular meta in the dashboard listing for a particular custom post type.
The custom field is the correct one, and I’m searching succesfully for it in other WP_Queries, but apparently what I’m doing here is not the proper way to do things, since my results remain unaffected. Code run throuh there properly, and I can see that $query->meta_query is set to my new WP_Meta_Query, but it doesn’t seem to matter.
Any clues on what I’m doing wrong? Is there a different hook should I be hooking into? A different way to create the new meta query for the existing query object?
Thanks in advance.
1 Answer
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' => '='
]
] );
}