WooCommerce:如何检查特定产品是否存在元密钥 [英] WooCommerce: How to check if meta key exists for a specific product
问题描述
情况:修改产品模板以仅在特定产品元存在/已设置/大于零时才显示一些 HTML(这是一种附加价格类型,它可以为空或正整数).
Situation: modifying the product template to display some HTML only IF a specific product meta exists / is set / greater-than-zero (it's an additional price type, it will either be empty or a positive integer).
实际的元是 WooCommerceMSRP 价格"的助推器,它作为元字段添加.
The actual meta is the Booster for WooCommerce "MSRP Price", which is added as a meta field.
所以这是有效的:echo do_shortcode('[wcj_product_meta name="_wcj_msrp"]');
但我只想在有问题的产品确实有 MSRP 集的情况下展示它(并非商店中的所有产品都有).对此的测试可以是非空"、已设置"或大于零".
But I only want to display it IF the product in question does have an MSRP set (not all the products in the store will). The test for this can be "not empty", "is set", or "greater than zero".
尝试以下语法:
<?php if ($product ->metadata_exists(_wcj_msrp)) {
echo '<li class="single-product-price price-msrp">MSRP: <span>$</span>';
echo do_shortcode( '[wcj_product_meta name="_wcj_msrp"]' );
echo '</li>';
}
?>
结果:页面无休止地加载.
Result: page loads endlessly.
我错过的简单愚蠢的事情是什么?
What is the simple stupid thing that I'm missing?
推荐答案
第一个 metadata_exist()
是 WordPress 条件函数,但不是 WC_Product
方法(或继承的 WC_Data
方法).这就是您的代码不起作用的原因,因为您没有使用 metadata_exist()
以正确的方式,因为该函数需要 3 个参数,并且不能用作 WC_Product
对象的方法.
First metadata_exist()
is a WordPress conditional function, but not a WC_Product
method (or an inherited WC_Data
method). That's why your code doesn't work, because you are not using metadata_exist()
in the right way as the function requires 3 arguments and can't not be used as a method on a WC_Product
Object.
假设您的简码可以正常工作,并且 WC_Product
对象已定义且可访问.您有 2 种可能性来检查产品是否存在元密钥(位于 wp_postmeta
表中):
Assuming that your shortcode works without problems, and that the WC_Product
Object is defined and accessible. You have 2 possibilities to check if a meta key exist for a product (located in wp_postmeta
table):
1) 使用 WooCommerce WC_Data
meta_exist()
(conditional) 这样的方法:
1) Using WooCommerce WC_Data
meta_exist()
(conditional) method this way:
<?php if ( $product->meta_exists( '_wcj_msrp' ) ) {
echo '<li class="single-product-price price-msrp">MSRP: <span>$</span>';
echo do_shortcode( '[wcj_product_meta name="_wcj_msrp"]' );
echo '</li>';
} ?>
2) 使用 metadata_exist()
WordPress这样的条件函数:
2) Using metadata_exist()
WordPress conditional function this way:
<?php if ( metadata_exists( 'post', $product->get_id(), '_wcj_msrp' ) ) {
echo '<li class="single-product-price price-msrp">MSRP: <span>$</span>';
echo do_shortcode( '[wcj_product_meta name="_wcj_msrp"]' );
echo '</li>';
} ?>
两者都应该有效.
这篇关于WooCommerce:如何检查特定产品是否存在元密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!