How to Add Custom Fields to Your WordPress Template File

By Lisa Sabin-Wilson

If you add a Custom Field to your own site, it may not appear the way you originally intended To get the data to display properly, you must open the template files and dig into the code a little bit.

You can add Custom Fields to your templates in several ways to display the output of the fields you’ve set. 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: Starts the PHP function. Every template tag or function needs to start PHP with <?php.
  • $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. In this example this call for post meta has three parameters:
    • ($post->ID: A parameter that dynamically defines the specific ID of the post being displayed so that WordPress knows which metadata to display.
    • $key,: A parameter that gets the value of the Custom Field based on the name, as defined in the $key="NAME“; setting earlier in the code string.
    • true);: A parameter that tells WordPress to return a single result rather than multiple results. (By default, this parameter is set to true; don’t change it unless you’re using multiple definitions in the Value setting of your Custom Field.)
  • ?>: Ends the PHP function.

The $key="mood"; part of the function tells WordPress to return the value for the Custom Field with the Name of mood.