0

I'm trying to find a way to have a conditional snippet in single.php where //do something happens if the current user has not commented on the current post.

I'm hopeless at coding but I'm guessing I need some of this...

is_user_logged_in()

$user_id = get_current_user_id()

The comment part baffles me... would this help? https://wordpress.stackexchange.com/questions/137799/how-to-limit-users-to-one-comment-per-post

  • 1
    I added some comments to the code that you referenced. Maybe that will help. – Dave Romsey Feb 26 '18 at 10:22
2

[EDIT] Here is the modified code:

$post_id = get_the_ID();          // ID of the current post.
$user_id = get_current_user_id(); // ID of the current user.
$post_author_id = get_post_field( 'post_author', $post_id );
$is_post_author = ( $user_id && $post_author_id == $user_id );
$can_comment = $is_post_author;

/*
 * If $can_comment is not yet TRUE, then it's because either:
 *   a) The user is not the author of the post; or
 *   b) The user is not registered on the site; or
 *   c) The user is logged-out.
 */
if ( $user_id && ! $can_comment ) {
    $comment_count = get_comments( array(
        'post_id' => $post_id,
        'user_id' => $user_id,
        'count'   => true,
    ) );

    $can_comment = empty( $comment_count );
}

if ( ! $is_post_author ) {
    if ( $can_comment ) {
        echo 'Post your comment.';
    } else {
        echo 'Sorry, you\'ve commented. Or you can\'t comment..';
    }
}
  • 1
    I've updated the code snippet. Check it out. – Sally CJ Feb 26 '18 at 15:50
  • 1
    Sorry if this sounds stupid, but are you sure? Because that's a bit odd. I've already tested the code and it worked well on my end. But it might be caused by some custom queries by your site's theme or a plugin. Try to add wp_reset_postdata(); before/above the $post_id = get_the_ID(); line and see if that helps. – Sally CJ Feb 27 '18 at 8:50
  • 1
    So, post authors can always comment on their own posts, even if they've already commented? If that's so, then I had really misunderstand the whole thing about the "excluding the current user's own posts". – Sally CJ Feb 28 '18 at 11:42
  • 1
    I've updated the code snippet. Check it out. (replace the previous one that you added to the single.php file) – Sally CJ Feb 28 '18 at 13:34
  • 1
    Try the updated code snippet. Hopefully, this time I got it right! =) – Sally CJ Mar 1 '18 at 1:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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