2

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

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

谢谢你的帮助

4

1 回答 1

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]
于 2019-06-09T23:46:10.030 回答