如何显示单个产品的所有订单,首先显示最近的订单?Woocommerce


How to display all orders for a single product showing the most recent first? Woocommerce

我在前端有一个密码保护的页面。在该页面上,我希望显示与单个woocommerce产品id关联的所有购买的完整列表。

选项1:

我看过woocommerce文档,我发现:WC_CLI_Order和一个列出所有订单的list_( $args, $assoc_args )函数。

可以推测,顺序可以通过product id

过滤。

[- =)根据order属性筛选订单。

行项字段(数字数组,从索引0开始):

line_items.0.product_id

选项2:

我找到了这篇文章,但它是基于客户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() ),
) );

如何显示单个产品的所有订单,首先显示最近的订单?

以下是我根据这些文章整理的解决方案:

  • http://www.wpbeginner.com/wp-themes/how-to-create-a-custom-page-in-wordpress/
  • https://wordpress.org/support/topic/how-to-show-all-orders-details-for-specific-or-particular-product-in-woocommerce-1/
  • https://www.gavick.com/blog/wp_query-woocommerce-products
解决方案

<?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>