我正在尝试按作者获取帖子数量(针对自定义帖子类型),首先我使用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
中。
我的方法正确吗?如果是,那出什么问题了?
谢谢
答案 0 :(得分:0)
使用用户ID作为所需作者的所有“食谱”帖子类型执行新的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);
答案 1 :(得分:0)
我没有找到任何解释为什么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;
}