While @Nikos and @blacksquare replies work, new message metadata is added to every order for every search. If you have 100 orders and 10 searches are being performed, the wp_postmeta table will have at least 100 * 10 = 1000 _product_sku entries. If some orders contain several products, there will be even more.
As @blacksquare suggested, add_post_meta should be called when the order is saved. However, if the site is small and the backend search performance is not too important, the following code will work without creating redundant _product_sku entries.
add_filter( 'woocommerce_shop_order_search_fields', 'my_shop_order_search_fields') ); public function my_shop_order_search_fields( $search_fields ) { $orders = get_posts( array( 'post_type' => 'shop_order', 'post_status' => wc_get_order_statuses(), //get all available order statuses in an array 'posts_per_page' => 999999, // query all orders 'meta_query' => array( array( 'key' => '_product_sku', 'compare' => 'NOT EXISTS' ) ) // only query orders without '_product_sku' postmeta ) ); foreach ($orders as $order) { $order_id = $order->ID; $wc_order = new WC_Order($order_id); $items = $wc_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 ); } } return array_merge($search_fields, array('_product_sku')); // make '_product_sku' one of the meta keys we are going to search for. }
While a better solution might be to call add_post_meta when creating an order, extra effort is needed to create _product_sku for existing orders, and you must create _product_sku for orders _product_sku until the code is activated. For simplicity, I would just use the solution proposed above.
ps @Nikos solution has one (controversial) advantage - if you change the SKU product after orders are made, Nikos decision to find those orders using the new SKU, while the above solution will not be. However, the SKU product should not be changed in any way, and it is debatable whether the search for new products should show old orders.
Ming yeung
source share