WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;
share|improve this question
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 – Pieter Goosen Jun 2 '14 at 4:27
up vote 0 down vote accepted

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); 
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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