1

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']) ? ' class="current"' : '';
    $views['missing_related'] = sprintf(__('<a href="%s"'. $class .'>Missing Related <span class="count">(%d)</span></a>', 'missing related'),
        admin_url('edit.php?post_type=my-cpt&norelated=1'),
        $result->found_posts);

    return $views;
}
0

I finally figured this out. What I had above is correct, as far as it goes. But the missing piece was changing the query based on that. So in addition, I needed to add the following code:

add_filter( 'parse_query','norelated_filter' );
function norelated_filter( $query ) {
  if( is_admin() AND $query->query['post_type'] == 'my-cpt' ) {
  if ($_GET['norelated']) {
    $qv = &$query->query_vars;
    $qv['meta_query'] = array(
    array(
     'key' => 'related',
     'compare' => 'NOT EXISTS'
    ));
    }
    }
    }
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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