简体   繁体   中英

WooCommerce Query Order Items by Product Meta

This is a bit of an odd one, but I'm having trouble finding an answer for how to do this:

I'm attempting to create a custom query that gets all the products (and their meta) which are contained within a WooCommerce order.

For example, let's say I have these orders pending:

Order A

  • Product 1
  • Product 2
  • Product 3

Order B

  • Product 4
  • Product 5
  • Product 6

My goal is to create a list based off these ordered products, which is ordered by the product's meta. Something like this:

Products with Meta Key A

  • Product 1
  • Product 3
  • Product 4

But again, these would only be products (including their quantities) that sit within an order.

The problem I'm facing is that "Order Items" and "Order Item Meta" as stored in the database are quite limiting and do not display all the information associated with a product. So in other words, I'm not finding a way to get to the info I need to create the loop to create my list.

My DB skills are limited so ideas would be appreciated!

Here is some related code that might help you:

add_filter( 'woocommerce_shop_order_search_fields', 'woocommerce_shop_order_search_product_cat' );

function woocommerce_shop_order_search_product_cat( $search_fields ) {

$args = array(
    'post_type' => 'shop_order'
    );

$orders = new WP_Query($args);

if($orders->have_posts()) {
        while($orders->have_posts()) {
        $post = $orders->the_post();
        $order_id = get_the_ID();
        $order = new WC_Order($order_id);
        $items = $order->get_items();
        foreach($items as $item) {
            $product_cats = wp_get_post_terms( $item['product_id'], 'product_cat' );
            foreach($product_cats as $product_cat) {
                add_post_meta($order_id, "_product_cat", $product_cat->name);
            }
        }
    }
};

$search_fields[] = '_product_cat';

return $search_fields;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM