【问题标题】:Get the total amount of orders for a given product获取给定产品的订单总量
【发布时间】:2017-03-10 20:41:50
【问题描述】:

我正在使用 WooCommerce,并且一直在使用此代码:

$units_sold = get_post_meta( get_the_ID(), 'total_sales', true );

此元返回已售出的商品数量。因此,如果有人购买了两件商品,那么它会返回两件。我想获得一种产品的订单数量,而不是售出的单位数量。

你知道我怎样才能轻松有效地获得这个号码吗?

谢谢

【问题讨论】:

    标签: php wordpress woocommerce product orders


    【解决方案1】:

    这是一个自定义函数,它将返回一种产品的订单数量。你有一个 $product_id 作为参数:

    function get_orders_count_for_a_product( $product_id ){
    
        $orders = wc_get_orders( array(
            'numberposts' => -1,
            'post_type' => 'shop_order',
            'post_status' => array('wc-completed') // completed status only
        ) );
    
        $count_orders = 0;
        foreach($orders as $order){
            $has_product = false;
            foreach($order->get_items() as $item_values)
                if( $item_values['product_id'] == $product_id )
                    $has_product = true;
            if( $has_product )
                $count_orders++;
        }
        return $count_orders;
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    用法:

    // Here Product ID is 125
    $the_product_id = 125; 
    $number_of orders = get_orders_count_for_a_product($the_product_id);
    // Output the value
    echo 'Number of orders for product ID ' . $the_product_id . ' is: '. $number_of orders;
    

    【讨论】:

    • 感谢@LoicTheAztec!非常感谢您的帮助,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 2021-12-06
    相关资源
    最近更新 更多