I’m trying to get the count of published posts in a custom post type for the current user (to display on a profile page).
I found this here on the forums:
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author="" . $curauth->ID . "" AND post_type="user_video" AND post_status="publish"");
?>
But, it’s just giving me a big fat ZERO even though there are definitely published posts of that type. What am I doing wrong and is there a better way to do this?
6 Answers
I’m posting a new answer because I found this thread while searching for the same thing and the solutions here weren’t optimal.
The post_type
argument can be a string or an array of post types.
function custom_count_posts_by_author($user_id, $post_type = array('post', 'page', 'custom_post_type'))
{
$args = array(
'post_type' => $post_type,
'author' => $user_id,
'post_status' => 'publish',
'posts_per_page' => -1
);
$query = new WP_Query($args);
return $query->found_posts;
}