作者:xiaoge | 来源:互联网 | 2023-10-12 10:20
我曾经使用标准wordpressWP_Query来获取基于元数据的woocommerce产品.我的产品是曲目,并有许多元列(如流派,乐器,心情等).使用WP_Query我可以根据表
我曾经使用标准wordpress WP_Query来获取基于元数据的woocommerce产品.我的产品是曲目,并有许多元列(如流派,乐器,心情等).使用WP_Query我可以根据表单中的用户输入创建meta_query,搜索符合元要求的产品.所有这一切都很棒.
现在我想使用wp_get_products而不是WP_Query,因为它是获取产品的新方式,并且应该比旧的方式更具有前瞻性.但是,我似乎无法弄清楚如何将meta_query传递给该函数.在github上宣布wc_get_products将支持2.8版本的meta.我能找到的唯一信息是以下链接:https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query(最后一段).
我尝试将meta_query作为一个数组数组传递,每个数组包含3个key-value对,用于键,值和比较,就像在WP_Query中一样.我还尝试将meta添加为Meta:meta-field-name,它是实际字段的名称,只有名称本身没有’meta’前缀,还有一些其他变种.这些方法都不起作用.任何人都可以告诉我,这个’自定义参数支持’是否只引用除meta字段以外的自定义参数,还是我做错了什么?
解决方法:
要在WC_Product_Query(位于wp_postmeta表中)处理产品自定义元数据,它安静简单并且可以工作,as explained in the very last paragraph of the related documentation.
But it doesn’t handle multiple values and comparison arguments like in a 07001, if you don’t set them in the function that extend the meta_query.
对于像_volume这样的自定义产品元键来处理产品在m3(立方米)中所采用的体积,以下代码将启用具有特定比较参数“大于”的自定义meta_key:
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handling_custom_meta_query_keys', 10, 3 );
function handling_custom_meta_query_keys( $wp_query_args, $query_vars, $data_store_cpt ) {
$meta_key = '_volume'; // The custom meta_key
if ( ! empty( $query_vars[$meta_key] ) ) {
$wp_query_args['meta_query'][] = array(
'key' => $meta_key,
'value' => esc_attr( $query_vars[$meta_key] ),
'compare' => '>', // <=== Here you can set other comparison arguments
);
}
return $wp_query_args;
}
代码位于活动子主题(或活动主题)的function.php文件中.
现在,您将根据特定的“比较”参数对此自定义_volume元键进行查询,以获得体积大于“0.2”的所有产品:
$queried_products = wc_get_products( array( '_volume' => '0.2' ) );
经过测试和工作.
As you can see, you can continue using a WP_Query
as many Woocommerce developers still do or even SQL queries through WordPress WPDB
Class…
The announced revolution around this is not going to come soon and I suppose that they will extend WC_Product_Query
and WC_Order_query
like WP_Query
with many more features and possibilities.