WP_Post_List_Table::get_views – Have post counts account for filters?

Toward the top of the edit.php screens there is a list that displays post statuses along with the post count. I believe this is generated by WP_Post_List_Table::get_views. For example All (7) | Published (6) | Draft (1)

Unfortunately, those post counts do not respect filters. I am using pre_get_posts to exclude certain posts. Even though only four posts are visible to the user, the numbers still reflect the total post count. I would like to see All (4) | Published (3) | Draft (1)

I can’t seem to find an action/filter to override these numbers (without using JavaScript).

2 Answers
2

You might want to remove those counts and replace them with your own.

function insert_post_counts($views){
    //Run your query to count posts
    //use wp_cache_set and wp_cache_get to optimize performance

    $edit_url = admin_url( 'edit.php' );

    $views['all'] = 'All <a href="'.$edit_url.'">('.$all_count.')</a>';
    $views['publish'] = 'Published <a href="'.$edit_url.'?post_status=publish">('.$publish_count.')</a>';
    $views['draft'] = 'Draft <a href="'.$edit_url.'?post_status=draft">('.$draft_count.')</a>';
    $views['trash'] = 'Trash <a href="'.$edit_url.'?post_status=trash">('.$draft_count.')</a>';

    return $views;
}
add_filter('views_edit-post, 'insert_post_counts', 10, 1);

You can reference how wp_count_posts works to generate the native post counts.

Hope this helps!

Leave a Comment