根据来自用户的活动成员身份显示/隐藏内容

时间:2019-06-09 19:45:53

标签: php wordpress woocommerce woocommerce-memberships

使用简码,无论用户是哪个会员计划,我都需要根据用户拥有的活跃会员数来显示内容。

我不是真的很喜欢PHP,但是我发现存在wc_memberships_get_user_memberships函数,因此想到了以这种方式开始。但这几乎是我的极限:

add_shortcode('count-active-memberships', 'count_active_memberships');
function count_active_memberships(){
$user_id = get_current_user_id();

$args = array( 
    'status' = 'active'
);  

$active_memberships = count(wc_memberships_get_user_memberships( $user_id, $args ));
}

最后看起来应该是

[count-active-memberships =“ 3”] 具有3个有效成员资格的成员的内容 [/ count-active-memberships]

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

注册简码时,回调函数count_active_memberships()最多接收2个参数:

  • 一个参数数组(传递给短代码的参数),和
  • 简码中的内容([count-active-memberships 这是内容 [/ count-active-memberships])。

如果仅当当前用户具有3个或更多活动成员身份时才想显示某些内容,可以执行以下操作:

add_shortcode('count-active-memberships', 'count_active_memberships');
function count_active_memberships($atts, $content = ''){
    $user_id = get_current_user_id();

    // The user is logged in, check memberships
    if ( $user_id ) {
        $args = array( 
            'status' => 'active'
        );
        $active_memberships = wc_memberships_get_user_memberships($user_id, $args);

        if ( is_array($active_memberships) && count($active_memberships) >= 3 ) {
            return $content;
        }
    }

    // User is either not logged in or doesn't have enough active memberships
    // so let's return an empty string.
    return '';
}

现在,如果您希望用户可以配置最低要求的成员资格数量,则需要在注册短代码的函数内定义一个新属性(例如min_memberships)。例如:

add_shortcode('count-active-memberships', 'count_active_memberships');
function count_active_memberships($atts, $content = ''){
    // Shortcode attributes
    $atts = shortcode_atts(array(
        'min_memberships' => 3
    ), $atts, 'count-active-memberships');

    // Let's make sure that the value passed by the user is a number
    if (
        ! is_numeric($atts['min_memberships']) 
        || $atts['min_memberships'] < 0
    ) {
        $atts['min_memberships'] = 3; // Fallback to minimum 3 memberships
    }

    $user_id = get_current_user_id();

    // The user is logged in, check memberships
    if ( $user_id ) {
        $args = array( 
            'status' => 'active'
        );
        $active_memberships = wc_memberships_get_user_memberships($user_id, $args);

        if (
            is_array($active_memberships) 
            && count($active_memberships) >= $atts['min_memberships']
        ) {
            return $content;
        }
    }

    // User is either not logged in or doesn't have enough active memberships
    // so let's return an empty string.
    return '';
}

然后您将可以执行以下操作:

[count-active-memberships min_memberships=5]
Content visible to users with 5 or more active memberships
[/count-active-memberships]