首页 > 解决方案 > 在 Woocommerce 中获取客户“保留”订单状态总金额

问题描述

我试图让 woocommerce 中的用户保留所有产品的价格(即用户已下订单但尚未付款)。

我有以下代码可以检测用户的所有产品搁置订单

function get_user_on_hold_product_price() {

    global $product, $woocommerce;

    // GET USER
    $current_user = wp_get_current_user();

    // GET USER ON-HOLD ORDERS
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $current_user->ID,
        'post_type'   => 'shop_order',
        'post_status' => 'wc-on-hold',
    ) );

我不确定从这里做什么才能仅获取用户所有搁置订单的总价格。

将此功能添加/挂钩到简码,如下所示;

add_shortcode('get_on-hold_price', 'get_user_on_hold_product_price')

谢谢

标签: phpwordpresswoocommerceshortcodeorders

解决方案


要使用 a 获取客户“暂停”订单的总量WC_Order_Query以提高可用性和兼容性:

add_shortcode('user_on_hold_total', 'get_user_orders_on_hold_total');
function get_user_orders_on_hold_total() {
    $total_amount = 0; // Initializing

    // Get current user
    if( $user = wp_get_current_user() ){

        // Get 'on-hold' customer ORDERS
        $on_hold_orders = wc_get_orders( array(
            'limit' => -1,
            'customer_id' => $user->ID,
            'status' => 'on-hold',
        ) );

        foreach( $on_hold_orders as $order) {
            $total_amount += $order->get_total();
        }
    }
    return $total_amount;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

要获得格式化的总金额,请替换return $total_amount;return wc_price($total_amount);

简码用法:[user_on_hold_total]

相关文档:Woocommercewc_get_orders()WC_Order_Query


推荐阅读