【问题标题】:Get customer's total paid orders sum in Woocommerce 3在 Woocommerce 3 中获取客户的总支付订单金额
【发布时间】:2018-02-17 12:49:55
【问题描述】:

例如,如果客户之前的购物记录超过 50k,那么他将获得 50% 的折扣。

这是我的代码,用于检索客户当前的订单价格,但我想检索总订单价格:

add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = '10percent'; // your coupon code here

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
    }

}

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce discount


    【解决方案1】:

    $user_id = get_current_user_id();

    $string = wc_get_customer_total_spent($user_id);

    回声 $string;

    【讨论】:

      【解决方案2】:

      您可以使用wc_get_customer_total_spent() 专用的 Woocommerce 功能,但此功能会获取所有已付款状态的订单(“处理中”和“已完成”)

      要获得所有客户购买的总和(仅针对“已完成”订单状态),您可以使用这个基于 wc_get_customer_total_spent() similar source code 的简单且轻量级的 SQL 来解决问题:

      global $wpdb;
      
      $user_id = get_current_user_id(); // Current user ID
      
      $user_purchases_total_sum = $wpdb->get_var( "
          SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}postmeta as pm
          INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
          INNER JOIN {$wpdb->prefix}postmeta as pm2 ON pm.post_id = pm2.post_id
          WHERE p.post_status LIKE 'wc-completed' AND p.post_type LIKE 'shop_order'
          AND pm.meta_key LIKE '_order_total' AND pm2.meta_key LIKE '_customer_user'
          AND pm2.meta_value LIKE $user_id
      " );
      

      经过测试并且有效。

      【讨论】:

        猜你喜欢
        • 2019-07-22
        • 2021-11-23
        • 2020-12-11
        • 1970-01-01
        • 2015-09-07
        • 2018-03-16
        • 2016-02-18
        • 1970-01-01
        相关资源
        最近更新 更多