Count posts by type including drafts and pending posts

I had this function that counts posts number by type (taken from wordpress codex)

function count_user_posts_by_type($userid, $post_type) {
    global $wpdb;
    $where = get_posts_by_author_sql($post_type, TRUE, $userid);
    $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} $where" );
    return apply_filters('get_usernumposts', $count, $userid);
}

and I changed it in order to display even posts with “draft” and “pending” status.

Read More
function count_user_posts_by_type($userid, $post_type) {
    global $wpdb;
    $where = get_posts_by_author_sql($post_type, TRUE, $userid);
    $count = $wpdb->get_var( "SELECT COUNT(*) 
                            FROM {$wpdb->posts} $where 
                            AND (post_status = 'publish' OR post_status = 'draft' OR post_status = 'pending')");
    return apply_filters('get_usernumposts', $count, $userid);
}

but it doesn’t work. If I echo the function like this

echo count_user_posts_by_type(wp_get_current_user()->ID, 'percorso');

I can see it counts just published posts. What’s wrong with what I wrote?
Thanks!

EDIT: as suggested, I performed a var_dump for SELECT COUNT etc. here’s what I got

string(216) 
    "SELECT COUNT(*) FROM mi_posts 
    WHERE post_author = 1 
    AND post_type = 'percorso' 
    AND (post_status = 'publish' OR post_status = 'private') 
    AND (post_status = 'publish' OR post_status = 'draft' OR post_status = 'pending')"

Related posts

Leave a Reply

1 comment

  1. It’s not necessary to use $wpdb, a simple get_posts can handle it. Check WP_Query for the full list of parameters.

    function count_user_posts_by_type( $userid, $post_type ) 
    {
        $args = array(
            'numberposts'   => -1,
            'post_type'     => $post_type,
            'post_status'   => array( 'publish', 'private', 'draft', 'pending' ),
            'author'        => $userid
        );
        $count_posts = count( get_posts( $args ) ); 
        return $count_posts;
    }