3

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 1

11

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' => '='
        ]
    ] );
}
4
  • Awesomeness. Thanks a lot. Every time I think I "get" WP, something else comes along. :)
    – user47133
    Commented Feb 4, 2015 at 11:48
  • Same for me ;-) Let me rephrase a famous quote by Niels Bohr, the Danish physicist: "If you think you can talk about WordPress without feeling dizzy, you haven't understood the first thing about it."
    – birgire
    Commented Feb 4, 2015 at 11:57
  • 1
    @birgire you missed a ) in your first if statement. Commented Dec 2, 2021 at 16:18
  • thanks for the heads up :-) @MichaelSchober
    – birgire
    Commented Dec 2, 2021 at 17:26

Your Answer

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