0

I'm borrowing from the code at Add filter menu to admin list of posts (of custom type) to filter posts by custom field values to add a filter to my custom post type with the parse_query filter:

function grievance_posts_filter( $query ){
    global $pagenow;
    $type = 'post';
    if (isset($_GET['post_type'])) {
        $type = $_GET['post_type'];
    }
    if ( 'grievance' == $type && is_admin() && $pagenow=='edit.php' && isset($_GET['step']) && $_GET['step'] != '') {
        $query->query_vars['meta_key'] = 'my_first_plugin_fields[step]';
        $query->query_vars['meta_value'] = 2;
    }
}
add_filter( 'parse_query', 'grievance_posts_filter' );

In the above code, I have hard-coded the value of the the meta_value to troubleshoot. I expect the above code to show me only the posts with the step value is set to "2". However, instead of filtering the posts, the edit.php page is not showing any posts at all. I don't think I'm using the right values for the meta_key and meta_value elements. I'm not sure what to put there. My meta_key has multiple sub-keys associated with it.

I have also tried:

        $query->query_vars['meta_key'] = 'my_first_plugin_fields';
        $query->query_vars['meta_value'] = array( 'step' => 2 );

but this did not work either.

I also attempted:

    $meta = [ 'my_first_plugin_fields' => [ 'key' => 'step', 'value' => '2', 'compare' => '=' ] ] ;
    $query->query_vars['meta_query'] = $meta;

without success.

2 Answers 2

0

Won't let me comment and possibly a silly question but have you tried putting die(); just after the if statement to be sure the conditional is working correctly?

Other wise I force meta values to become terms in an hidden taxonomy and utilize those as filters. I can expand on that if you like but don't want to go that way too much as that isn't the topic of the question.

1
  • Yes, the code in the statement is definitely getting executed. I verified by removing the "if" statement.
    – StevieD
    Oct 29, 2019 at 14:00
0

I was able to accomplish this with:

        $query->query_vars['meta_key'] = 'my_first_plugin_fields';
        $query->query_vars['meta_value'] = sprintf(':"step";s:1:"%s";', $_GET['step']);
        $query->query_vars['meta_compare'] = 'LIKE';

Which seems like an awful hack. If there is a better way, I'd love to hear.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.