I have created 5 custom meta values for my products on WC but not every product have all custom fields.
At the moment, I am displaying the meta data like so:
<div class="meta">
<?php if($product->get_meta('metabox_animal') != '') echo '<div class="type"><p>Row One</p></div>' . $product->get_meta('metabox_animal'); ?>
<?php if($product->get_meta('metabox_medical') != '') echo '<div class="type"><p>Row Two</p></div>' . $product->get_meta('metabox_medical'); ?>
<?php if($product->get_meta('metabox_general') != '') echo '<div class="type"><p>Row Three</p></div>' . $product->get_meta('metabox_general'); ?>
<?php if($product->get_meta('metabox_capacity') != '') echo '<div class="type"><p>Row Four</p></div>' . $product->get_meta('metabox_capacity'); ?>
<?php if($product->get_meta('metabox_pet') != '') echo '<div class="type"><p>Row Five</p></div>' . $product->get_meta('metabox_pet'); ?>
</div>
Is there a way that I can create a loop that will cycle through all of the meta values and if they exist, display them but if they’re blank / empty / not used show a container ‘NOT APPLICABLE’?
Any help would be greatly appreciated!
3
Answers
This not tested and only one way you might get this done:
Sure!
You can create an array of all the meta terms that you need to retrieve.
Following your code this is the code you will need. Of course you can add/remove as you see fit.
So… what the hell did we do here?
First we created an array of all the meta data that we need to retrieve.
After we created that array we need to start an iteration to get, check and display each meta data.
For that we use a foreach (PHP foreach).
ok
In the foreach block, using the variable $meta_term that contains the meta string that we need to retrieve we now use it to get the product meta data.
Now we check if the meta data is not empty, using the !empty() function, if it’s not empty than we know that there is value we can output so, using echo we can now build the proper html.
Hope this help =D
You can set your related data in an array, then use a foreach loop as follow and if a custom field value is empty or doesn’t exist, "NOT APPLICABLE" will be displayed instead (code is commented):
I have changed a bit your html. If it’s not convenient and you want to keep yours, just replace:
by this line: