Adding Custom Fields to Your Template File

If you followed along in theprevious sections and added the mood Custom Field to your own site, notice that the data doesn't appear on your site the way it does on Lisa's. To get the data to display properly, you must open the template files and dig into the code a little bit. If the idea of digging into the code of your template files intimidates you, you can put this section aside and read up on WordPress themes, template files, and template tags in Book VI.

You can add Custom Fields, in several ways, to your templates in order to display the output of the fields you've set; we think the easiest way involves using the get_post_meta(); template tag function, which looks like this:

<?php $key=“NAME”; echo get_post_meta($post->ID, $key, true); ?>

Here's how that function breaks down:

  • <?php: Part of the functions begins PHP. (Every template tag or function needs to first start PHP with <?php. You can read more about basic PHP in Book II, Chapter 3.)
  • $key=“NAME”;: Defines the name of the key that you want to appear. You define the Name when you add the Custom Field to your post.
  • echo get_post_meta: Grabs the Custom Field data and displays it on your site.
  • $post->ID,: A parameter of the get_post_meta function that dynamically defines the specific ID of the post being displayed so that WordPress knows which metadata to display.
  • $key,: A parameter of the get_post_meta function that gets the value of the Custom Field based on the name, as ...

Get WordPress® All-in-One For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.