2

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?

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? Commented Oct 28, 2016 at 2:48

2 Answers 2

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.";
}
1
  • 1
    It's perfect @dalv, it worked really nice, Thanks a lot. Commented Oct 28, 2016 at 0:43
6

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
}
2
  • Do you use that by itself or does it integrate with the previous answer?
    – Pete
    Commented May 29, 2019 at 8:59
  • 1
    by iteself. but now i see i've missed something, let me edit.
    – Ituk
    Commented May 29, 2019 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.