Wednesday 24 July 2013

Getting WordPress to check for your Custom Field

The previous sections show you how to add the necessary code to your
template file to display your Custom Field; however, what if you want to
publish a post on which you don’t want the mood Custom Field to appear?
If you leave your template file as you set it up by following the steps in the
previous sections, even if you don’t add the mood Custom Field, your blog
post displays My Current Mood is: — without a mood because you didn’t
define one.

But you can easily make WordPress check first to see whether the Custom
Field is added. If it finds the Custom Field, WordPress displays your mood; if
it doesn’t find the Custom Field, then WordPress doesn’t display anything.
If you followed along in the previous sections, 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 and, 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. Refer to the “IF, ELSE” sidebar, in this chapter, to see some everyday situations that explain the IF question. Apply this statement to the code you just added to your template and you get:
IF the mood Custom Field exists, then WordPress will display it, or ELSE it won’t.

0 comments:

Post a Comment