Show content only if member left a comment

Check if the user has left a comment

// the user may have commented on *any* post
define( 'CHECK_GLOBAL_FOR_COMMENTS', TRUE );

//
// some more code
//

function memberviparea( $atts, $content = null ) {

    $post_id = 0;

    // if the user have to left a comment explicit on this post, get the post ID
    if( defined( 'CHECK_GLOBAL_FOR_COMMENTS' ) && FALSE === CHECK_GLOBAL_FOR_COMMENTS ) {
        global $post;

        $post_id = ( is_object( $post ) && isset( $post->ID ) ) ?
            $post->ID : 0;
    }

    if( is_user_logged_in() && user_has_left_comment( $post_id ) )
        return '<p>' . $content . '</p>';
    else
        return;

}

/**
 * Check if the user has left a comment
 *
 * If a post ID is set, the function checks if
 * the user has just left a comment in this post.
 * Otherwise it check if the user has left a comment on
 * any post.
 * If no user ID is set, the ID of the current logged in user is used.
 * If no user is currently logged in, the fuction returns null.
 *
 * @param int $post_id ID of the post (optional)
 * @param int $user_id User ID (required)
 * @return null|bool Null if no user is logged in and no user ID is set, else true if the user has left a comment, false if not
 */
function user_has_left_comment( $post_id = 0, $user_id = 0 ) {

    if( ! is_user_logged_in() && 0 === $user_id )
        return NULL;
    elseif( 0 === $user_id )
        $user_id = wp_get_current_user()->ID;

    $args = array( 'user_id' => $user_id );

    if ( 0 !== $post_id )
        $args['post_id'] = $post_id;

    $comments = get_comments( $args );

    return ! empty( $comments );

}

This function will check if the user has left a comment on the current post. If you want to check if the user generally left a comment (on any post), delete or comment out this line 'post_id' => $pid, // get only comments from this post and

Update

Because such a function could be usefull, I rewrite the code a bit to make it easier to reuse it. Now it is possible to check if the user left a comment on any post or on a specific post by passing the post ID to the function.

Leave a Comment