2016-11-12 77 views
0

我在前端有一個受密碼保護的頁面。在該頁面上,我想顯示與單個woocommerce產品ID關聯的所有購買的完整列表。如何顯示顯示最近的第一個產品的所有訂單? Woocommerce

選項1:

我已經通過了woocommerce docs一看,我發現: WC_CLI_Orderlist_($args, $assoc_args)功能,列出了所有的訂單。

據推測,訂單可以通過product id

過濾[ - =]基於順序屬性 過濾訂單。

訂單項字段(數值數組,開始與指數零):

line_items.0.product_id 

選項2:

found this article,但它是基於客戶ID。我修改了基於meta_key和meta_value猜測的代碼。

$customer_orders = get_posts(array(
    'numberposts' => -1, 
    'meta_key' => '_product', 
    'meta_value' => get_product_id(), 
    'post_type' => wc_get_order_types(), 
    'post_status' => array_keys(wc_get_order_statuses()), 
)); 

如何顯示顯示最近訂單的單個產品的所有訂單?

+0

有您是否嘗試更改查詢以根據您的產品購買產品?像get_purchases(array('product'=>'pencil'))它正在構建查詢玩具的需求。我不是woocommerce的專家。但我認爲這些數組應該是一個查詢鍵如meta_value是不需要的,如果它不在您的表中 –

回答

2

這裏是我放在一起基於這些文章的解決方案:

解決方案

<?php /* Template Name: CustomPageT1 */ ?> 
<?php 
global $wpdb; 
$produto_id = 41; // Product ID 
$consulta = "SELECT order_id " . 
      "FROM {$wpdb->prefix}woocommerce_order_itemmeta woim " . 
      "LEFT JOIN {$wpdb->prefix}woocommerce_order_items oi " . 
      "ON woim.order_item_id = oi.order_item_id " . 
      "WHERE meta_key = '_product_id' AND meta_value = %d " . 
      "GROUP BY order_id;"; 

$order_ids = $wpdb->get_col($wpdb->prepare($consulta, $produto_id)); 

foreach($order_ids as $order_id) { 
    var_dump($order_id); 
} 

if($order_ids) { 
    $args = array(
     'post_type' => 'shop_order', 
     'post__in' => $order_ids, 
     'post_status' => 'publish', 
     'posts_per_page' => 20, 
     'order' => 'DESC', 
     'tax_query' => array(
      array(
       'taxonomy' => 'shop_order_status', 
       'field' => 'slug', 
       'terms' => array (
        'Pending' , 'Failed' , 'Processing' , 'Completed', 'On-Hold' , 'Cancelled' , 'Refunded' 
       ) 
      ) 
     ) 
    ); 
    $wc_query = new WP_Query($args); 
} 

?> 

// Display products 
<div> 
    <?php if ($wc_query->have_posts()) : ?> 
    <?php while ($wc_query->have_posts()) : // (4) 
        $wc_query->the_post(); // (4.1) ?> 

    <ul> 
     <li> 
      <?php the_title(); // (4.2) ?> 
     </li> 
    </ul> 

    <?php endwhile; ?> 
    <?php wp_reset_postdata(); // (5) ?> 
    <?php else: ?> 
    <p> 
     <?php _e('No Orders'); // (6) ?> 
    </p> 
    <?php endif; ?> 
</div> 
+0

感謝您的解決方案,對我的需求非常滿意。請注意,WooCommerce> 2.2不再爲訂單狀態使用分類法。你應該使用post_status來代替。 –

相關問題