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