仅当成员留下评论时才显示内容

时间:2013-02-08 作者:M.UNLU

函数Php:

add_shortcode( \'membervip\', \'memberviparea\' );
function memberviparea( $atts, $content = null ) {
    if( is_user_logged_in() ) return \'<p>\' . $content . \'</p>\';
    else return;
}
职位:

[会员VIP]Lorem ipsum dolor sit amet,concetetuer adipiscing elit,sed diam nonumm nibh euismod tincidunt ut laoreet dolore magna aliquam erat vollpat。[/会员VIP]

使用此代码,我可以只显示登录成员的链接,但我只想显示已登录并发表评论的成员的链接。

什么代码可以做到这一点?

1 个回复
最合适的回答,由SO网友:Ralf912 整理而成

检查用户是否留言

// 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 );

}
此函数将检查用户是否在current 邮递如果要检查用户是否通常在any 删除或注释掉这一行\'post_id\' => $pid, // get only comments from this post and

Update

因为这样一个函数可能很有用,所以我稍微重写了代码,使其更易于重用。现在可以检查用户是否在any 通过将post ID传递给函数来发布或发布特定的post。

结束