简体   繁体   English

Woocommerce默认角色和购买后的角色

[英]Woocommerce default role and role after purchase

I found this thread but it doesn't exactly do what I'm looking for. 我找到了这个线程,但是它并不能完全满足我的需求。

My question is, how can I change the default Woocommerce role "customer" to, eg "Subscriber" for new registered users. 我的问题是,如何将新的注册用户的默认Woocommerce角色“客户”更改为“订户”。 And then, if user checks out (purchases product), change the role from "Subscriber" to "Customer". 然后,如果用户签出(购买产品),则将角色从“订户”更改为“客户”。

I'm asking this as I want to show different content per user roles: "registered customer" and "subscribed (paid) customer". 我之所以这样询问,是因为我希望针对每个用户角色显示不同的内容:“注册客户”和“订阅(付费)客户”。

The first part of your question is changing the default role of user that is created by WooCommerce. 问题的第一部分是更改由WooCommerce创建的默认用户角色。 Honestly, I'd probably leave the default role as customer. 老实说,我可能会保留默认角色为客户。 And then create a new role/capability for people who purchase your specific product. 然后为购买您特定产品的人员创建新的角色/功能。

add_filter( 'woocommerce_new_customer_data', 'so_29647785_default_role' );

function so_29647785_default_role( $data ){
    $data['role'] = 'subscriber'; // the new default role
    return $data;
}

As you saw in my other answer (well my re-posted answer), you can do things once the user has finished paying, but hooking into the woocommerce_order_status_completed hook. 正如您在我的其他答案(以及我重新发布的答案)中所看到的那样,您可以在用户完成付款后执行操作,但是请插入woocommerce_order_status_completed挂钩。

To adapt that code to do something specific to a particular product, you need to loop through the order items and check them against a product ID. 为了使代码适合特定产品的特定功能,您需要遍历订单项并根据产品ID检查它们。 Replace 999 with the ID of the product in question. 用相关产品的ID替换999。

add_action( 'woocommerce_order_status_completed', 'so_29647785_convert_customer_role' );

function so_29647785_convert_customer_role( $order_id ) {

    $order = new WC_Order( $order_id );

    if ( $order->user_id > 0 ) {

        foreach ( $order->get_items() as $order_item ) {

            if( 999 == $order_item[ 'product_id' ] ) {
                $user = new WP_User( $order->user_id );

                // Remove existing role
                $user->remove_role( 'customer' ); 

                // Add new role
                $user->add_role( 'subscriber' );        
            }

        }

    }
} 

Note: Totally untested, but seems right in theory. 注意:完全未经测试,但在理论上似乎是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM