I’m trying to hide the display of custom fields if they have no values. If I display them with the_meta, then the headers show, whether or not there are any values in the Custom Fields.
It generates this html:
<ul class="post-meta">
<li>
<span class="post-meta-key">My Custom Field Title</span>
</li>
<li>
</ul>
I really don’t want titles on the page if there’s no content. So I tried:
<?php
$ck = get_post_custom_keys($post_id); //Array
foreach ($ck as $k) {
$cv = get_post_custom_values($k, $post_id ); //Array
foreach ($cv as $c) {
echo (' - ');
echo ($c);
}
}
?>
Echo for $c (the custom values applied to the post) looks like this:
With no values:
- 1 – 1343633746:1 – – field_5014a45c9a2df – field_5014a48c38f9d – – field_5014a48c2cc82
With values:
- 1 – 1343603999:1 – 3 cups of eggs – field_5014a45c9a2df – field_5014a48c38f9d – 2 cups of flour – field_5014a48c2cc82
This is probably the long way to go about it. It’s showing values for things like “last edit” too, not just the two fields that I put in to test.
How I can show the Custom Fields only if they have values? I’m writing a theme, so I do not know the names of the fields, or how many, beforehand.
Thanks!
You can check for empty values with
empty(), you can check if the field starts with underscore (internal values like_edit_last) and skip those.