Show/Hide 内容基于用户的活跃会员数量

Show/Hide content based on number of active memberships from user

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

我不是很喜欢 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]

感谢您的帮助

当您注册简码时,您的回调函数 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]