获取客户 1 年内在 WooCommerce 中的总支出

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

使用根据用户在 WooCommerce 中的总支出显示自定义文本中的代码:

add_shortcode('user_total_spent', 'get_user_total_spent');
function get_user_total_spent( $atts ) {

    extract( shortcode_atts( array(
        'user_id' => get_current_user_id(),
    ), $atts, 'user_total_spent' ) );

    if( $user_id > 0 ) {
        $customer = new WC_Customer( $user_id ); // Get WC_Customer Object

        $total_spent = $customer->get_total_spent(); // Get total spent amount

        if( $total_spent > 600 && $total_spent < 1200 ){
            $text = __( 'congrats you are now tier 1', 'woocommerce' );
        }elseif( $total_spent > 1200 ){
            $text = __( 'congrats you are now tier 2', 'woocommerce' );
        }else{
            $text = __( 'congrats you are now tier 3', 'woocommerce' );
        }

        $total_spent = wc_price( $total_spent );

        return "Total Amount Spent: ".$total_spent." ".$text;
    }
}

此代码接收客户的总支出。

有没有办法从客户“已完成”订单中获取仅过去一年的总支出?

例如,如果今天是 2024/03/24,则总支出应仅针对 2023/03/24 至 2024/03/24 期间“已完成”订单的总和。

php wordpress woocommerce shortcode orders
1个回答
0
投票

您可以使用以下自定义实用程序函数来获取“已完成”客户在特定时期(去年)的总支出:

// Utility function: Get customer orders total amount from specific status on a period
function get_orders_total_for( $user_id, $period = '1 year', $status = 'completed' ) {
    global $wpdb;
    return $wpdb->get_var( $wpdb->prepare( "
        SELECT SUM(total_amount)
        FROM {$wpdb->prefix}wc_orders
        WHERE status = %s
        AND customer_id = %d
        AND date_created_gmt >= %s
    ", 'wc-'.$status, $user_id, date('Y-m-d H:i:s', strtotime('-'.$period) ) ) );
}

然后您可以在简码功能中使用它,例如:

add_shortcode('user_year_total_spent', 'get_user_year_total_spent');
function get_user_year_total_spent( $atts ) {
    extract( shortcode_atts( array(
        'user_id' => get_current_user_id(),
    ), $atts, 'user_year_total_spent' ) );

    if( ! $user_id ) return;

    $total_spent = get_orders_total_for( $user_id ); // Get total spent amount

    if( $total_spent >= 1200 ) {
        $text = __('Congrats you are now tier 3.', 'woocommerce');
    } elseif ( $total_spent >= 600 ) {
        $text = __('Congrats you are now tier 2.', 'woocommerce');
    } else {
        $text = __('Congrats you are now tier 1.', 'woocommerce');
    }
    return sprintf(__('Total Amount Spent: %s. %s', 'woocommerce'), wc_price($total_spent), $text);
}

代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。

短代码用法:

  • 在 WP 帖子/页面编辑器或某些小部件中:
    [user_year_total_spent]
  • 在 PHP 代码中:
    echo do_shortcode('[user_year_total_spent]');
© www.soinside.com 2019 - 2024. All rights reserved.