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, then 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: <?php $key=mood; echo get_post_meta($post- >ID, $key, true); ?></strong></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: <?php $key=mood; echo get_post_meta($post- >ID, $key, true); ?></strong></p> <?php endif; ?>
The first line is an IF statement followed by an ELSE statement. It basically, asks the question: Does the mood metadata exist for this post? If it does, the data gets displayed. If it doesn’t, then 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. If the mood Custom Field exists, then WordPress will display it, or else it won’t.