Enhance your custom theme – Part 2

Step 2: Check to see if custom field exist

It’s a good idea to use conditional statements and display the custom field only if it exists.

<?php $quote = get_post_meta($post->ID, 'page-quote', true);
 //Checking if anything exists for the key page-quote
  if ($quote) {
    echo $quote;
  } else {
    echo "You forgot to insert a quote...";
} ?>

To keep things simple we will remove the line that has – < ?php get_sidebar(); ?> in our page.php template and replace it with:

<div id="sidebar" class="quote">
<?php $quote = get_post_meta($post->ID, 'page-quote', true);
 if ($quote) { ?>
  <p><?php echo $quote; ?></p>
 <?php } else { ?>
  <p>"You forgot to insert a quote..."</p>
 <?php } ?>

This condition needs to go before closing the loop. You should now have quotes displaying in your sidebar and the class=”quote” allows you to style the quotes as you wish.

NOTE: You’ll notice that custom fields do not contain any html characters, thus in our example above, if you wanted to display the credit in bold, you will need to wrap the authors’ name in bold tags.

Comments are closed.