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?
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.I would suggest using
get_posts()
instead ofquery_posts()
for your purpose.It also looks simpler now 🙂
OK, after more Googleing, this seems to work without having to use MySQL and dive into the database directly:
In authors profile for me works great this (ait-dir-item is custom post type name)
You need to declare $wpdb as global as well, and use its prefix method.
https://codex.wordpress.org/Function_Reference/count_user_posts