Get all ordered item attribute in woocommerce

I am creating custom report that following this script. It works fine, but I need to know how to get the all ordered product attributes.

include_once(WC()->plugin_path().'/includes/admin/reports/class-wc-admin-report.php');
$wc_report = new WC_Admin_Report();

$sold_products = $wc_report->get_order_report_data( array(
    'data' => array(
        '_product_id' => array(
            'type' => 'order_item_meta',
            'order_item_type' => 'line_item',
            'function' => '',
            'name' => 'product_id'
        ),
        '_qty' => array(
            'type' => 'order_item_meta',
            'order_item_type' => 'line_item',
            'function' => 'SUM',
            'name' => 'quantity'
        ),
        '_line_subtotal' => array(
            'type' => 'order_item_meta',
            'order_item_type' => 'line_item',
            'function' => 'SUM',
            'name' => 'gross'
        ),
        '_line_total' => array(
            'type' => 'order_item_meta',
            'order_item_type' => 'line_item',
            'function' => 'SUM',
            'name' => 'gross_after_discount'
        )
    ),
    'where' => array(
        array(
            'key'      => 'order_items.order_item_name',
            'value'    => '%shirt%',
            'operator' => 'LIKE',
        ),
    ),

    'group_by'     => 'order_item_name',

    'query_type' => 'get_results',

    'limit' => 20,

    'order_status' => array( 'completed', 'processing' ),
) );

  foreach($sold_products as $product){
      //how to we get the attributes of each sold product? 
  } 
}

I can see attributes are stored in _woocommerce_order_itemmeta table, I can use the ‘data’ above to get it one by one. But the thing is if some attributes only applied to certain product, which will caused the query above searched no result. So it would be better to get all of the ordered item attributes at once.

Read more here: Get all ordered item attribute in woocommerce

Leave a Reply

Your email address will not be published. Required fields are marked *