微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在Woocommerce 3上的WC_Product_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添加MetaMeta-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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐