简体   繁体   中英

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' ?

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM