更新(2019 年)
以下自定义条件函数有一个可选参数$user_id(定义的用户id),当当前用户(或定义的用户)返回true有有效的订阅。
所以现在可以使用 3 种不同的方式来完成 (做同样的事情):
1) 使用 WooCommerce 订阅专用条件函数wcs_user_has_subscription():
function has_active_subscription( $user_id='' ) {
// When a $user_id is not specified, get the current user Id
if( '' == $user_id && is_user_logged_in() )
$user_id = get_current_user_id();
// User not logged in we return false
if( $user_id == 0 )
return false;
return wcs_user_has_subscription( $user_id, '', 'active' );
}
2) 使用更轻量级的 SQL 查询实现同样的功能(于 2019 年 3 月添加):
function has_active_subscription( $user_id=null ) {
// When a $user_id is not specified, get the current user Id
if( null == $user_id && is_user_logged_in() )
$user_id = get_current_user_id();
// User not logged in we return false
if( $user_id == 0 )
return false;
global $wpdb;
// Get all active subscriptions count for a user ID
$count_subscriptions = $wpdb->get_var( "
SELECT count(p.ID)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm
ON p.ID = pm.post_id
WHERE p.post_type = 'shop_subscription'
AND p.post_status = 'wc-active'
AND pm.meta_key = '_customer_user'
AND pm.meta_value > 0
AND pm.meta_value = '$user_id'
" );
return $count_subscriptions == 0 ? false : true;
}
代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。
3) 原来的增强代码,同样会做同样的事情:
function has_active_subscription( $user_id=null ) {
// When a $user_id is not specified, get the current user Id
if( null == $user_id && is_user_logged_in() )
$user_id = get_current_user_id();
// User not logged in we return false
if( $user_id == 0 )
return false;
// Get all active subscriptions for a user ID
$active_subscriptions = get_posts( array(
'numberposts' => 1, // Only one is enough
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_subscription', // Subscription post type
'post_status' => 'wc-active', // Active subscription
'fields' => 'ids', // return only IDs (instead of complete post objects)
) );
return sizeof($active_subscriptions) == 0 ? false : true;
}
代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。
使用情况更新:
1) 当前用户的使用情况:
if( has_active_subscription() ){ // Current user has an active subscription
// do something … here goes your code
// Example of displaying something
echo '<p>I have active subscription</p>';
}
2) 已定义用户 ID 的使用情况:
if( has_active_subscription(26) ){ // Defined User ID has an active subscription
// do something … here goes your code
// Example of displaying something
echo '<p>User ID "26" have an active subscription</p>';
}
此代码已经过测试并且可以正常工作
相关答案: