最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Check if author or current user has posts published

programmeradmin0浏览0评论

I'm doing a QUIZ system, but I'm facing a problem that I dont know how to fix it.

I need to make a if basically, where it will check if the current user has a post published, as the question title. It's important to say that the posts are a specifically custom-post-type, so I need to check if there is a post with a certain post-type with the author-id equal to the current user ID.

Can someone help-me?

I'm doing a QUIZ system, but I'm facing a problem that I dont know how to fix it.

I need to make a if basically, where it will check if the current user has a post published, as the question title. It's important to say that the posts are a specifically custom-post-type, so I need to check if there is a post with a certain post-type with the author-id equal to the current user ID.

Can someone help-me?

Share Improve this question edited Jul 26, 2017 at 21:06 CommunityBot 1 asked Oct 27, 2016 at 23:17 Claudio BonfatiClaudio Bonfati 1251 silver badge5 bronze badges 1
  • Glad I could help! And sorry about the echo, I tested it using error_log and then forgot to take out the brackets. Could you maybe change the question title to 'Check if author or current user has posts published' or something that's more easy to find in search? – Alex Protopopescu Commented Oct 28, 2016 at 2:48
Add a comment  | 

2 Answers 2

Reset to default 4

Using get_posts or WP_query with similar $args:

$args = array(
    'post_type'  => 'your_custom_post_type',
    'author'     => get_current_user_id(),
);

$wp_posts = get_posts($args);

if (count($wp_posts)) {
    echo "Yes, the current user has 'your_custom_post_type' posts published!";
} else {
    echo "No, the current user does not have 'your_custom_post_type' posts published.";
}

diving into this I found that count_user_posts() is a better solution. it's shorter, and also cheaper in resources than get_posts();

so here it is:

$user_id = get_current_user_id(); //the logged in user's id
$post_type = 'your-post-type-here';
$posts = count_user_posts( $user_id, $post_type ); //cout user's posts
if( $posts > 0 ){
  //user has posts
}
发布评论

评论列表(0)

  1. 暂无评论