WooCommerce: Search By Custom Field

The default WooCommerce frontend product search returns results based on whether the search term is present in the product title, SKU, short and long description.

But what if you also want to search inside a custom field i.e. you have a custom field called “_brand” and you also want to search by “_brand”?

Now, I’m not sure I’ve explained this in plain English, so let’s take a look at a practical example. Enjoy!

With the snippet below, and if I had “Puma” saved in the “_brand” custom field for some products, this search result would actually return those products!

PHP Snippet: Search Products By Custom Field Value @ WooCommerce Search

The only thing you need to change in the snippet below is ‘_brand‘. Change it to the key of your custom field, and you should get results based on that. Let me know in the comments if it works!

/**
 * @snippet       Search By Custom Field @ WooCommerce Search
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_filter( 'posts_search', 'bbloomer_product_search_by_custom_field' );

function bbloomer_product_search_by_custom_field( $where ) {
    global $wpdb, $wp;
    if ( is_admin() || ! is_search() || ! isset( $wp->query_vars['s'] ) || 'product' != $wp->query_vars['post_type'] ) {
        return $where;
    }
    $product_ids = array();
    $terms = explode( ',', $wp->query_vars['s'] );
    foreach ( $terms as $term ) {		
		$products = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_parent FROM {$wpdb->posts} LEFT JOIN {$wpdb->postmeta} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id WHERE meta_key IN ( '_brand' ) AND meta_value LIKE %s;", '%' . $wpdb->esc_like( wc_clean( $term ) ) . '%' ) );       
		$products = array_merge( wp_list_pluck( $products, 'ID' ), wp_list_pluck( $products, 'post_parent' ) );
        if ( sizeof( $products ) > 0 ) {
            $product_ids = array_merge( $product_ids, $products );
        }
    }
    $product_ids = array_filter( array_unique( array_map( 'absint', $product_ids ) ) );
	if ( sizeof( $product_ids ) > 0 ) {
        $where = str_replace( 'AND (((', "AND ( ({$wpdb->posts}.ID IN (" . implode( ',', $product_ids ) . ")) OR ((", $where );
    }	
    return $where;	
}
Was this article helpful?
YesNo

Where to add custom code?

You should place PHP snippets at the bottom of your child theme functions.php file and CSS at the bottom of its style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my guide "Should I Add Custom Code Via WP Editor, FTP or Code Snippets?" and my video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything went as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting.

If you think this code saved you time & money, feel free to join 17,000+ WooCommerce Weekly subscribers for blog post updates and 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance!

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza.

4 thoughts on “WooCommerce: Search By Custom Field

  1. thanks this worked for me. So, is it possible to add more than one meta field to this structure?

    1. Hello Mehmet, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. Hi there,

    When I use your code in a Code Snippet, it generates a warning in the logs:

    "PHP Warning:  Undefined array key "post_type" in ..."

    Any suggestions to improve this code?

    Kind regards,

    Marc

    1. I don’t see any “post_type” array key in my snippet, so this may be because of something else (a plugin or theme)

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

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