根据WooCommerce年度订单数更改用户角色 [英] Change user role based on WooCommerce yearly orders count

查看:67
本文介绍了根据WooCommerce年度订单数更改用户角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一项功能,即在完成一定数量的订单后,客户将获得新的用户角色,但是所有这些订单必须在同一年内完成.

I'm trying to implement a feature where customers receive a new user role after a certain amount of orders have been made, but all those orders must have been made within the same year.

我能够基于第n个订单来分配用户角色,但似乎无法超出需要考虑日期的地方,有人可以向我指出正确的方向或指出我可能会做些什么丢失.

I was able to assign the user role based on nth number of orders but can't seem to go beyond to where the date needs to be taken into consideration, can someone point me in the right direction or point out what I might be missing.

这是我到目前为止尝试过的.

This is what I have tried so far.

function change_user_role_on_order_status_completed( $order_id ) {

    $order = new WC_Order( $order_id );

    $user_id = $order->user_id;

    $order_this_year = false;

    $current_date = date('Y');

    $total_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $user_id,
        'post_type'   => 'shop_order',
    ) );

    if ( $total_orders > 1 ) {
        foreach ($order->get_items() as $item_key => $item_values):

            // Get the item date
            if ($item_date = $item_values->get_date_completed()->format ('Y') == $current_date) {
                $order_this_year = true;
            }

        endforeach;

        if ($order_this_year) {
            $user = new WP_User( $order->user_id );

            // Set role editor
            $user->set_role( 'customer_club' ); 
        }

    }
}

add_action( 'woocommerce_order_status_completed', 'change_user_role_on_order_status_completed', 10, 1 );

推荐答案

使用 WC_Order_Query 此处是一种基于年度订单数更改用户角色的更轻松,更简单的方法:

Using WC_Order_Query here is a much lighter and simple way to change the user role based on yearly orders count:

add_action( 'woocommerce_order_status_completed', 'change_user_role_on_order_status_completed', 10, 2 );
function change_user_role_on_order_status_completed( $order_id, $order ) {
    // Here set the minimal order count
    $min_orders_count = 3;

    // The WC_Order_Query
    $queried_orders = wc_get_orders( array(
        'limit'        => -1,
        'customer_id'  => $order->get_customer_id(),
        'date_paid'    => '>=' . date('Y') . '-01-01', // or 'date_created'
        'return'       => 'ids'
    ) );

    if ( sizeof($queried_orders) >= $min_orders_count ) {
        // Get an instance of the customer WP_User Object
        $user = $order->get_user();

        // Change the user role
        $user->set_role( 'customer_club' );
    }
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于根据WooCommerce年度订单数更改用户角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆