Woocommerce pre_get_posts query variation meta data not working

In wordpress I made a simple plugin that adds a function to the pre_get_posts hook.

I need to be able to search products by their variation sku. The query seems to work as when I var_dump the posts returned by the WP_Query they actually include the correct posts(products). But the search result page doesn't show them and display No products were found matching your selection. no matter what theme I use.

The code I tied:

function awesome_plugin_init() {

    function is_woocommerce_really_activated() {
        if ( class_exists( 'woocommerce' ) ) { return true; } else { return false; }
    }
    
    if(is_woocommerce_really_activated()) {
        add_action('pre_get_posts', function( $query ) {

            if ( $query-is_search  is_search() ){
            
                $search = $query-get( 's' );

                $query-set( 'meta_key', '_sku' );
                $query-set( 'meta_value', $search );
                $query-set( 'meta_compare', 'LIKE' );

            }

            /*  This would return the correct post, yet still doesn't show up in search results:
                $q = new WP_Query([
                    'post_type' = ['product', 'product_variation'],
                    'meta_query' = [
                        [
                            'key' = '_sku',
                            'value' = $search,
                            'compare' = 'LIKE'
                        ]
                    ]
                ]);
            */

                
        });
    }
    
}
add_action( 'plugins_loaded', 'awesome_plugin_init' );

Topic woocommerce-offtopic pre-get-posts Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.