[英]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.在 WooCommerce 中使用
wc_get_products()
function 我想找到一种使用LIKE
运算符按名称过滤产品的方法。
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 '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.如果您查看“添加自定义参数支持”部分末尾的
WC_Product_Query
的 WooCommerce 官方文档,您将看到您可以使用自定义挂钩 function 操作 WC_Product_Query。
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:因此,要使用产品名称“LIKE”参数过滤查询,您可以使用搜索“s”参数扩展查询,这将起到如下作用:
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).代码进入您的活动子主题(或活动主题)的functions.php 文件。 tested and works.
测试和工作。
USAGE example with custom argument "like_name":使用自定义参数“like_name”的用法示例:
$args = array(
'limit' => 5,
'like_name' => 'test',
);
wc_get_products( $args );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.