Correct Post Count ( All | Published | Drafts | Pending | Trash ) for Custom Post Type when restricting to view own posts

You have to change:

'post_type'   => 'post',

To:

'post_type'   => 'your_custom_post_type_name',

And a all the reference to standard post. Also, you should add the filters only for main query or you can end up with issues in secondary queries. Bellow an example code for gallery custom post type. I was trying to debug the code you posted (taken from somewhre) but finally I’ve decided to post a working code I already use, which is much cleaner (it doesn’t include the counter for media (uploads) but, as your question suggest, you have not problems with that).

add_action( 'pre_get_posts', function( $query ) {

    //Note that current_user_can('edit_others_posts') check for
    //capability_type like posts, custom capabilities may be defined for custom posts
    if( is_admin() && ! current_user_can('edit_others_posts') && $query->is_main_query() ) {

        $query->set('author', get_current_user_id());

        //For standard posts
        add_filter('views_edit-post', 'views_filter_for_own_posts' );

        //For gallery post type
        add_filter('views_edit-gallery', 'views_filter_for_own_posts' );

        //You can add more similar filters for more post types with no extra changes
    }

} );

function views_filter_for_own_posts( $views ) {

    $post_type = get_query_var('post_type');
    $author = get_current_user_id();

    unset($views['mine']);

    $new_views = array(
            'all'       => __('All'),
            'publish'   => __('Published'),
            'private'   => __('Private'),
            'pending'   => __('Pending Review'),
            'future'    => __('Scheduled'),
            'draft'     => __('Draft'),
            'trash'     => __('Trash')
            );

    foreach( $new_views as $view => $name ) {

        $query = array(
            'author'      => $author,
            'post_type'   => $post_type
        );

        if($view == 'all') {

            $query['all_posts'] = 1;
            $class = ( get_query_var('all_posts') == 1 || get_query_var('post_status') == '' ) ? ' class="current"' : '';
            $url_query_var="all_posts=1";

        } else {

            $query['post_status'] = $view;
            $class = ( get_query_var('post_status') == $view ) ? ' class="current"' : '';
            $url_query_var="post_status=".$view;

        }

        $result = new WP_Query($query);

        if($result->found_posts > 0) {

            $views[$view] = sprintf(
                '<a href="https://wordpress.stackexchange.com/questions/178236/%s"'. $class .'>'.__($name).' <span class="count">(%d)</span></a>',
                admin_url('edit.php?'.$url_query_var.'&post_type=".$post_type),
                $result->found_posts
            );

        } else {

            unset($views[$view]);

        }

    }

    return $views;
}

Leave a Comment