How to Hide a WordPress Custom Field
If you have added Custom Fields to your WordPress blog template, you might not always want them on display. WordPress has a self-check search enabling blog posts without the Custom Field to appear automatically. If you leave your template file as you set it up, your blog post displays the Key Name by itself whether or not a Value is added.
You can easily make WordPress check the Custom Field. If it finds the Custom Field, WordPress displays your added Value; if it doesn’t find the Custom Field, WordPress doesn’t display anything. For example, if your Key Name reads “My Mood Is ____” but you don’t add the Value “Happy”, the Custom Field, with the search enabled, will not post to your blog.
Using mood as an example, the code in your template looks like this:
<p><strong>My Current Mood is:<strong> <em><?php $key="mood"; echo get_post_meta($post->ID, $key, true); ?></em></p>
To make WordPress check to see whether the mood Custom Field exists, add this code to the line above your existing code:
<?php if ( get_post_meta($post->ID, 'mood', true) ) : ?>
Then add this line of code to the line below your existing code:
<?php endif; ?>
Put together, the lines of code in your template should look like this:
<?php if ( get_post_meta($post->ID, 'mood', true) ) : ?> <p><strong>My Current Mood is:</strong> <em><?php $key="mood"; echo get_post_meta($post->ID, $key, true); ?></em></p> <?php endif; ?>
The first line is an IF statement and basically asks, “Does the mood key exist for this post?” If it does, the value gets displayed. If it doesn’t, WordPress skips over the code, ignoring it completely so that nothing gets displayed for the mood Custom Field. The final line of code simply puts an end to the IF question.
Apply this statement to the code you just added to your template and you get this: IF the mood Custom Field exists, then WordPress will display it, or ELSE it won’t.