I have a custom post type, and on the main admin edit list screen I would like to add a filter (in addition to All, Pending, Drafts, etc) to show only posts that are missing a particular meta_key. I can get the link and proper count to show up, but when clicked on, all the items are still showing, not just the filtered items found. Here is my code:

    add_action('pre_get_posts', 'query_add_filter' );
function query_add_filter( $wp_query ) {
    if( is_admin()) {
        add_filter('views_edit-my-cpt', 'filter_cpt');
    }
}

// add filter
function filter_cpt($views) {
    global $wp_query;

    $query = array(
        'post_type'   => 'my-cpt',
        'meta_query' => array(
              array(
               'key' => 'related',
               'compare' => 'NOT EXISTS'
                ),
           )
         );
    $result = new WP_Query($query);
    $class = ($wp_query->query_vars['norelated'] == 'yes') ? ' class="current"' : '';
    $views['publish_f'] = sprintf(__('<a href="%s"'. $class .'>Missing Related <span class="count">(%d)</span></a>', 'missing related'),
        admin_url('edit.php?post_type=my-cpt&norelated=yes'),
        $result->found_posts);

    return $views;
}

Read more here: views_edit-post filter not working (custom post type)


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: