在 WooCommerce 订阅激活时分配自定义用户角色

问题描述 投票:0回答:1

在 WooCommerce 中,我需要在用户的订阅生效时自动为其分配自定义角色(“活跃生产公司”)。角色分配将仅允许活跃订阅者访问并提交网站上使用 WP Job Manager 创建的受限表单。

我添加了 WooCommerce 订阅产品(按月和按年)供用户购买,这会在成功付款后授予他们自定义角色。

这是我当前使用的代码:

add_action( 'woocommerce_subscription_status_updated', 'wc_subscribe_assign_role', 10, 3 );

function wc_subscribe_assign_role( $subscription, $new_status, $old_status ) {
   if ( $new_status === 'active' ) {
       $user_id = $subscription->get_user_id(); // Get the user ID of the subscriber
       $user = new WP_User( $user_id );
        
        // Assign the "Active Production Company" role upon subscription activation
        $user->set_role( 'active_production_company' );
    }
}

我不确定是否正确使用

$subscription
来获取用户 ID,或者
woocommerce_subscription_status_updated
是否是用于此目的的最佳钩子。

我使用了

woocommerce_subscription_status_updated
钩子,希望它能在订阅状态更改为“活动”时触发角色分配。我希望这会自动将“Active Production Company”角色分配给用户,从而允许他们访问受限表单。

使用测试订单进行测试后,没有应用预期的角色。我检查了 WooCommerce 订阅对象文档和错误日志,但无法确认 $subscription->get_user_id() 部分是否按预期工作。对于可靠地实现此功能的任何见解或建议,我将不胜感激!

php wordpress woocommerce user-roles woocommerce-subscriptions
1个回答
0
投票

请注意,

WC_Subscription
对象从WC_Abstract_Order
WC_Order
类继承方法
,因此您可以使用:

  • get_user()
    方法,获取
    WP_User
    对象,
  • get_user_id()
    方法,获取用户ID。

现在您可以更好地使用

woocommerce_subscription_status_active
复合过滤器钩子,该钩子在订阅激活时触发。

请注意,您应该添加自定义角色,而不是替换当前用户角色,因为

subscriber
角色是由 WooCommerce 订阅插件分配和使用的。

这是一个简化的代码版本:

 // Add "Active Production Company" role upon subscription activation
add_action( 'woocommerce_subscription_status_active', 'add_role_to_active_subscribers', 10 );
function add_role_to_active_subscribers( $subscription ) {
    $custom_role =  'active_production_company'; // Custom user role to add
    $user = $subscription->get_user(); // Get the WP User object

    // If user has not yet the custom user role
    if( is_a( $user, 'WP_User' ) && ! in_array(  $custom_role, (array) $user->roles ) ) {
        $user->add_role( $custom_role ); // Add custom role
    }
}

应该可以。

如果你真的愿意,你可以随时使用

set_role()
方法而不是
add_role()

© www.soinside.com 2019 - 2024. All rights reserved.