Entering the Custom Field Code in the WordPress Template File
So that you can see how to enter the Custom Field code in your template file, the WordPress theme Twenty Sixteen in these instructions. If you’re using a different theme (thousands of WordPress themes are available), you need to adapt these instructions to your particular theme.
Follow these steps to add the template tag to your theme, along with a little HTML code to make it look nice. (These steps assume that you’ve already added a Custom Field to your blog post and assigned a value to it.)
- Log in to your WordPress Dashboard.
- Click the Editor link on the Appearances menu.
The Edit Themes screen loads in the Dashboard.
- Locate the template files for your theme (in this case, Twenty Sixteen).
The available templates are listed on the right side of the Edit Themes page.
content-single.phpin the list of templates.
content-single.phptemplate opens in the text editor on the left side of the screen, where you can edit the template file.
- Scroll down and locate the template tag that looks like this:
</div><!-- .entry-content -->
- On the new line directly above the line in Step 5, type this:
<p><strong>My Current Mood is:</strong><em>
<strong>open the HTML tags for paragraph and bold text, respectively, followed by the words to display in your template (
My Current Mood is:).
<em>opens the HTML tag for italic-style text, which gets applied to the value.
- Type the PHP that makes the custom field work:
<?php $key="mood"; echo get_post_meta($post->ID, $key, true); ?>
</em></p>.This code closes the HTML tags you opened in Step 6.
- Click the Update File button.
Located at the bottom of the Edit Themes screen, this button saves the changes you made in the
content.phpfile and reloads the page with the message that your changes have been successfully saved.
- View your post on your site to see your Custom Field data displayed.
WordPress displays your current mood at the bottom of the posts to which you added the mood Custom Field.
The entire code, put together, should look like this in your template:
<p><strong>My Current Mood is:</strong> <em><?php $key="mood"; echo get_post_meta($post->ID, $key, true); ?></em></p>
The code is case-sensitive, which means that the words you enter for the key in your Custom Field need to match the case of the
$key in the code. If you enter
mood in the Key field, for example, the code needs to be lowercase as well:
$key="mood". If you attempt to change the case to
$key="Mood", the code won’t work.
You have to add this code for the
mood Custom Field only one time. After you add the template function code to your template for the
mood Custom Field, you can define your current mood in every post you publish on your site by using the Custom Fields interface.
This example is just one type of Custom Field that you can add to your posts.