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).
The actual meta is the Booster for WooCommerce “MSRP Price”, which is added as a meta field.
So this works: echo do_shortcode( '[wcj_product_meta name="_wcj_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”.
Trying the following syntax:
<?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?
3
Answers
Figured it out. Thanks, LoicTheAztec, for putting me on the right path! :)
Tested it, works correctly. If there IS a value in the MSRP field, it outputs the LI and its proper contents. If the MSRP field is empty, it outputs nothing.
Life lesson here is: don't check for whether a metadata field exists, because it might exist regardless. Check whether it's empty or not.
Answered, closed, thank you!
I don’t know much about wordpress,but i took a look and for what i’ve see that metadata_exists requires the meta type, the object id and meta key. Maybe you should check your implementation on $product ->metadata_exists().
First
metadata_exist()
is a WordPress conditional function, but not aWC_Product
method (or an inheritedWC_Data
method). That’s why your code doesn’t work, because you are not usingmetadata_exist()
in the right way as the function requires 3 arguments and can’t not be used as a method on aWC_Product
Object.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 inwp_postmeta
table):1) Using WooCommerce
WC_Data
meta_exist()
(conditional) method this way:2) Using
metadata_exist()
WordPress conditional function this way:Both should work.