How to Add a Custom Field as a Searchable Field in the WooCommerce Backend Order Creation Page

By default, the “Add Product” modal in the WooCommerce backend order creation page allows searching for products by name and SKU. However, if you have a custom field for your products and would like to make it searchable as well, you can easily add this functionality using a custom code snippet.

To add a custom field as a searchable field in the “Add Product” modal, follow these steps:

  1. Determine the name of the custom field you want to add as a searchable field. For example, let’s say your custom field is called “Product Code”.
  2. Open your theme’s functions.php file or create a new plugin for your custom code snippets.
  3. Add the following code snippet to the file:
// Add custom field as a searchable field in the Add Product modal
add_filter( 'woocommerce_product_pre_search_products', 'wp_daily_product_search', 10, 6 );
function wp_daily_product_search( $result, $term, $type, $include_variations, $all_statuses, $limit ) {
	global $wpdb;
	if ( isset( $term ) && ! empty( $term ) ) {
		// Search for product IDs that have a matching 'product_code' meta value
		// Replace "product_code" with the name of your custom field
		$product_ids = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT DISTINCT post_id
                 FROM $wpdb->postmeta
                 WHERE meta_key = 'product_code' 
                 AND meta_value LIKE %s",
				'%' . $wpdb->esc_like( $term ) . '%'
			)
		);
		
		// If product IDs are found, use them to filter the search results
		if ( $product_ids ) {
			$result = array_merge( (array) $result, $product_ids );
		}
	}
	
	return $result;
}
  1. Replace “product_code” in the code snippet with the name of your custom field.
  2. Save the file and refresh the backend order creation page.

After adding this code snippet, you should be able to search for products by your custom field as well as by name and SKU in the “Add Product” modal. Just start typing the value of your custom field in the search field, and the modal will automatically display the matching products.

Adding a custom field as a searchable field in the WooCommerce backend order creation page can save you time and make it easier to find the products you need. Give it a try and see how it works for you!

Leave a Comment

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