Sometimes you will need to get the number of posts that a user has created.
This can also apply to Custom Post Types.
Checking WordPress' codex we can see count_user_posts which counts exactly what it
promises but doesn't do anything for custom post types.
Fortunately, somebody has added a function that can be used in the meantime.
[code]
function count_user_posts_by_type( $user_id, $post_type = 'post' ) {
global $wpdb;
$where = get_posts_by_author_sql( $post_type, true, $user_id );
$count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
return apply_filters( 'get_usernumposts', $count, $user_id );
}
[/code]
Here is another way
[code]
/**
*
* Usage: count_user_posts_by_type_alt(0, 'movie');
*
* @global obj $wpdb
* @param int $user_id 0 will get the currently logged in user's ID.
* @param string $post_type
* @return int
* @author Slavi Marinvo | http://orbisius.com
*/
function count_user_posts_by_type_alt( $user_id = 0, $post_type = 'post' ) {
global $wpdb;
$user_id = $user_id ? $user_id : get_current_user_id();
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE
post_type = %s AND post_author = %d ", $post_type, $user_id ) );
return apply_filters( 'get_user_num_posts', $count, $user_id );
}
[/code]