You have the right idea about saving extra metadata to the order. As jbby and helgatheviking suggest, there is no built-in postmeta for product_id or sku available by default in the woocommerce orders api. Your methodology for accessing and saving the metadata wasn't quite right, however. wp_get_post_terms
will access custom taxonomy information, not metadata (use get_post_meta
for that). You will be able to do what you were trying to do with this filter:
add_filter( 'woocommerce_shop_order_search_fields', function ($search_fields ) {
$posts = get_posts(array('post_type' => 'shop_order'));
foreach ($posts as $post) {
$order_id = $post->ID;
$order = new WC_Order($order_id);
$items = $order->get_items();
foreach($items as $item) {
$product_id = $item['product_id'];
$search_sku = get_post_meta($product_id, "_sku", true);
add_post_meta($order_id, "_product_sku", $search_sku);
add_post_meta($order_id, "_product_id", $product_id);
}
}
return array_merge($search_fields, array('_product_sku', '_product_id'));
});
Strictly speaking you should probably move the calls to add_post_meta
into a hook that runs when the order is originally saved to the database--this will prevent unnecessary legwork whenever you search through order.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…