gpt4 book ai didi

php - 在 WooCommerce 中的 WC_Product_Query 上按名称 "LIKE"过滤产品

转载 作者:行者123 更新时间:2023-12-04 16:27:01 28 4
gpt4 key购买 nike

在 WooCommerce 中使用 wc_get_products()功能 我想找到一种方法,使用 LIKEname 过滤产品运算符。

实际上,我只能通过特定定义的名称过滤产品:

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

是否可以过滤名称为 LIKE 'test' 的产品?

最佳答案

如果您查看 WooCommerce official documentation for WC_Product_Query“添加自定义参数支持”部分的末尾,您将看到您可以使用自定义 Hook 函数来操作 WC_Product_Query。

因此,要使用产品名称“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;
}

代码在您的事件子主题(或事件主题)的functions.php 文件中。经过测试并且有效。


USAGE 示例,带有自定义参数“like_name”:

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

wc_get_products( $args );

关于php - 在 WooCommerce 中的 WC_Product_Query 上按名称 "LIKE"过滤产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62069128/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com