WooCommerce访问有产品销售的订单

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

在WooCommerce中,我有这个功能循环所有订单并获得有优惠券折扣的订单:

$orders = wc_get_orders( array('numberposts' => -1) );

// Loop through each WC_Order Object
foreach( $orders as $order ){
    if ( sizeof($order->get_used_coupons()) > 0 ) {
        $order_data = $order->get_data(); // The Order data
        $data = 'Order Number: #' . $order->id . '<br>' .'Order Status: '. $order->status . '<br>' . 'Order Creation Date: ' . $order_date_created = $order_data['date_created']->date('Y-m-d H:i:s') . '<br>' . 'Order Total: '. $order->total . '<br>' . 'Customer Username: ' . $order_billing_first_name = $order_data['billing']['first_name'] . '<br>' . 'Customer E-Mail: '. $order_billing_email = $order_data['billing']['email'] . '<br>' . 'Customer Phone: ' . $order_billing_phone = $order_data['billing']['phone'] . '<br>'; 
    }

}  

而不是优惠券,是否有可能获得所有销售产品的订单?我怎么能这样做?

php sql wordpress woocommerce orders
1个回答
1
投票

更新:以下内容将让您获得包含“待售”商品的WooCommerce订单。

具有自定义SQL查询的函数,该查询通过“待售”项目获取订单ID:

// Get Orders Ids with "on sale" items
function wc_get_onsale_items_order_ids() {
    global $wpdb;

    // The paid order statuses
    $statuses = implode( "','wc-", array_map( 'esc_sql', wc_get_is_paid_statuses() ) );

    // The_query
    return $wpdb->get_col("
        SELECT DISTINCT o.ID
        FROM {$wpdb->prefix}posts o
        INNER JOIN {$wpdb->prefix}postmeta om
            ON o.ID = om.post_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items oi
            ON o.ID = oi.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim
            ON oi.order_item_id = oim.order_item_id
        WHERE o.post_type = 'shop_order'
        AND o.post_status IN ('wc-$statuses')
        AND oim.meta_key IN ('_product_id','_variation_id')
        AND oim.meta_value IN (
            SELECT p.ID
            FROM {$wpdb->prefix}posts p
            INNER JOIN {$wpdb->prefix}postmeta pm
                ON p.ID = pm.post_id
            WHERE p.post_type IN ('product','product_variation')
            AND p.post_status = 'publish'
            AND pm.meta_key = '_sale_price'
            AND pm.meta_value != ''
            AND pm.meta_value > 0
        )
    ");
}

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


在您的代码中使用:

// Loop through each WC_Order Object
foreach( wc_get_onsale_items_order_ids() as $order_id ){
    // Get The WC_Order Object
    $order = wc_get_order( $order_id );

    // The dormatted data
    $data = 'Order Number: #' . $order->get_order_number() . '<br>' .
        'Order Status: '. $order->get_status() . '<br>' . 
        'Order Creation Date: ' . $order->get_date_created()->date('Y-m-d H:i:s') . '<br>' . 
        'Order Total: '. $order->get_total() . '<br>' . 
        'Customer Username: ' . $order->get_billing_first_name() . '<br>' . 
        'Customer E-Mail: '.  $order->get_billing_email() . '<br>' . 
        'Customer Phone: ' . $order->get_billing_phone(); 
    }
}  
© www.soinside.com 2019 - 2024. All rights reserved.