Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter products by name "LIKE" on a WC_Product_Query in WooCommerce

In WooCommerce using wc_get_products() function I would like to find a way to filter products by name using the LIKE operator.

Actually I am only able to filter products by a specific defined name with:

$args = array(
    'limit' => 5,
    'name' => 'Test',
);
$result = wc_get_products( $args );

Is it possible to filter products where the name is LIKE 'test'?

like image 682
Stefano Vet Avatar asked Oct 20 '25 04:10

Stefano Vet


1 Answers

If you look to WooCommerce official documentation for WC_Product_Query at the end on the section "Adding Custom Parameter Support" you will see that you can manipulate the WC_Product_Query with a custom hooked function.

So to filter the query with a product name "LIKE" parameter, you can extend the query with the search "s" argument, that will do the trick as follow:

add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 );
function handle_custom_query_var( $query, $query_vars ) {
    if ( isset( $query_vars['like_name'] ) && ! empty( $query_vars['like_name'] ) ) {
        $query['s'] = esc_attr( $query_vars['like_name'] );
    }

    return $query;
}

Code goes in functions.php file of your active child theme (or active theme). tested and works.


USAGE example with custom argument "like_name":

$args = array(
    'limit' => 5,
    'like_name' => 'test',
);

wc_get_products( $args );
like image 170
LoicTheAztec Avatar answered Oct 22 '25 18:10

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!