Site icon Hip-Hop Website Design and Development

Expand stock search to specific metadata fields

In a WP+Woo installation I would like to expand the stock search in such a way that in addition to searching among the product titles also search among the variation/single product SKUs, and variation descriptions.

I don’t want to install a plugin for this, so I researched get_posts() and its relevant hooks to find the proper place to hook my own code to add the functionality I needed. The hook that seemed more promising was do_action_ref_array( 'pre_get_posts', WP_Query $query ) so I wrote the following code:

add_action('pre_get_posts', 'extend_product_search', 10, 1);
function extend_product_search($query)
{
    if (!is_admin() && $query->is_main_query()) {
        if (is_search()) { //|| is_tax()) {
            if ($query->query['post_type'] == 'product') {
                $query->query['post_type'] = $query->query_vars['post_type'] = array('product', 'product_variation');
                $query->meta_query = array(
                    0 => array(
                        'key' => '_sku',
                        'value' => $query->query['s'],
                    ),
                    1 => array(
                        'key' => '_variation_description',
                        'value' => $query->query['s'],
                    ),
                    'relation' => 'OR',
                );
                $query->query['s'] = ''; // <-- More on this line in the question
                $query->query_vars['s'] = ''; // <-- More on this line in the question

                echo '<pre>' . print_r($query, true) . '</pre>'; // <--- This is for debugging purposes only
            }
        }
    }
}

This way I can add the necessary meta_query args in order to expand the search to the additional data. However, the problem is this:

Is there a way that I’m missing (though WP_Query is very well documented, so I doubt I’ve missed something), that could turn that AND into an OR in the first case mentioned above? Something like the relation arg that determines the relation among the meta_query args.

Also, could it be that do_action_ref_array( 'pre_get_posts', WP_Query $query ) is not that proper hook point to hook my point in the first place?

Please someone with experience on this? TIA.