I'm trying to add some custom views/filters to the list of posts for a custom post type in the admin. However, the query that counts the number of posts is updating the number of posts for all filters at once, only if I am on one of those custom filters.

This is how I've set up the query that gets the number of posts:

add_action( 'views_edit-movies', array($this, 'custom_views') );
public function custom_views($views) {
    //$directors is a valid array returned from seperate function, removed for clarity
    foreach ($directors as $key => $value) {
        $director = $value;
        $query = array(
           'post_type' => 'movies',
           'meta_key' => 'director',
           'meta_value' => $director
        $result = new WP_Query($query);

        $class = ($wp_query->query_vars['meta_value'] == $director) ? ' class="current"' : '';
        $views["$director"] = sprintf(__('<a href="%s"'. $class .'>' . $director . ' <span class="count">(%d)</span></a>'),
    }//end foreach

This works fine if I am on the "All", "Published", or "Trash" default views, and each director filter has the correct number of posts on those views. When I then click on a director, all other directors have the same number of posts as the one as I am currently on.

Is this because I'm assigning the views within a foreach loop, based on a variable? Or because I'm changing the query to display the view with the code below?

Here is the code that actually displays the views:

add_action( 'pre_get_posts', array($this, 'filters') );
public function filters($query)
    if ( isset($_GET['director']) ) {
        $query->set( 'meta_key', 'director' );
        $query->set( 'meta_value', $_GET['director'] );
    return $query;
  • You should post this as an answer. You might even score yourself some reputation points that are vital to use more functionality on the site Commented Jun 2, 2014 at 4:27

1 Answer 1


The issue was that the $query->set in the filter function was updating the main query used to count the number of posts. Likely due to the order in which they were called. I tried to flush and run a new wp_query but what ultimately worked best was the function below that uses a custom query.

public function count($director)
 $num = $this->wpdb->get_results("SELECT * FROM " . $this->wpdb->prefix . "postmeta WHERE meta_key = 'directory' AND meta_value = '".$director."'"); 
 return count($num); 

Your Answer

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

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