0

I am editing the comments.php file for the purpose of my site. I want the comment section to be something like this: only the person who made the first comment and the post author will be able to create the next comments one by one. My code goes something like this now. This doesn't work as in the $current_user->ID == $challengerName doesn't work..

$challengerName = '';

global $post, $current_user;

$commentNum = get_comments_number();

if ( $commentNum < 10 ) {
    if ( $commentNum == 0 ) {
        if ( $post->post_author == $current_user->ID ){

        }
        else{
                    comment_form($comment_args);
        }
    }

    if ( $commentNum == 1 ) {
        $challengerName = get_comment_author();

        if ( $post->post_author == $current_user->ID ) {
                        comment_form($comment_args);
        }
        else{

        }

    }
//This handles until comment number 1
if ( $commentNum > 1) {

    if ($commentNum % 2 == 0) {
        if ( $post->post_author == $current_user->ID ){

        }
        elseif ($current_user->ID == $challengerName)
        {
                    comment_form($comment_args);
        }   
    }
    else{
        if ( $post->post_author == $current_user->ID ){
                        comment_form($comment_args);
        }
        else{

        }
    }
}
}//Check end if number of comments is 10 or less
else
{
    echo "Debate Over";
}
1

Helper function

Here's a helper function (untested) to check if a given user ID is the first commenter for a given post ID:

/**
 * Check if a given user ID is the first commenter for a given post ID
 *
 * @param int   $user_id User ID
 * @param int   $post_id Post ID
 * @return bool True/False
 */
function wpse_is_user_first_commenter( $user_id = 0, $post_id = 0 )
{
    $first_comment = get_comments( 
        [ 
            'status'  => 'approve', 
            'number'  => 1, 
            'order'   => 'ASC', 
            'orderby' => 'comment_date_gmt',
            'post_id' => (int) $post_id, 
        ] 
    );

    if( empty( $first_comment ) )
        return false;

    return $first_comment[0]->user_id === $user_id;
}

Usage example:

Check if the current user is the first commenter of the current post:

if ( wpse_is_user_first_commenter( get_current_user_id(), get_the_ID() ) )
{
    // ...
}

Hope you can adjust it to your needs!

  • 1
    The helper function could also perfectly be used in the comments_open filter (to keep functionality even when switching themes) – kero Jul 16 '17 at 17:40

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.