If you manage an online store and you use SKUs to manage the control of your products, inventory or whatever you need, sooner or later you are going to discover that WooCommerce by default does not allow you to search for orders by SKU.
This, for an effective management of any online store that uses SKUs is a problem that, fortunately, has an easy solution, simply by adding a few lines of code that get the order browser to work as it always should.
The code is this:
/* Allow search in orders by SKU */
add_filter( 'woocommerce_shop_order_search_results', 'wphelp_search_order_by_sku', 9999, 3 );
function wphelp_search_order_by_sku( $order_ids, $term, $search_fields ) {
global $wpdb;
if ( ! empty( $search_fields ) ) {
$product_id = wc_get_product_id_by_sku( $wpdb->esc_like( wc_clean( $term ) ) );
if ( ! $product_id ) return $order_ids;
$order_ids = array_unique(
$wpdb->get_col(
$wpdb->prepare( "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key = '_product_id' AND meta_value = %d ) AND order_item_type = 'line_item'", $product_id )
)
);
}
return $order_ids;
}
Code language: PHP (php)
If you don’t know how or where to add this code here is a quick and easy guide:
How and where to paste in WordPress PHP, JS, CSS codes and functions you find out there.
Once you have added the code, WooCommerce will now allow you to search for orders by SKU.