我试图获取作者的帖子数量(对于自定义帖子类型),首先我使用count_user_posts($userID , 'recipe')
然后我试图解决这个问题:
function nbrPostByUser( $userid, $post_type = ['recipe'] ) {
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 );
}
它总是返回0 ....调试后我认为原因是我的自定义帖子类型不包含在全局$wp_post_types
中。
我的方法是否正确?如果是的话会出错?
谢谢
为用户ID作为所需作者的所有“recipie”帖子类型执行新的get_posts。
// Prepare the query arguments
$args = [
'posts_per_page' => -1,
'post_type' => 'article',
'author' => 1,
'post_status' => 'publish',
];
// Get all the posts
$posts = get_posts($args);
// Return the count of all the recipies for a user:
return count($posts);
我没有找到任何解释为什么wordpress返回0自定义帖子类型,所以我解决了我的问题,使用$ wpdb好朋友这里是我正在使用的功能,它的工作就像一个魅力:
function getNbrPostsByUser($userId, $postType){
global $wpdb;
$nbrPost = $wpdb->get_var( $wpdb->prepare(
"
SELECT COUNT(*)
FROM $wpdb->posts
WHERE post_type = %s AND post_author = %d AND post_status = 'publish'
",
$postType,
$userId
) );
return $nbrPost;
}