To extend greater functionality out of WordPress I wanted to show you how easy it is to add and code custom fields into posts or pages in WordPress. Custom fields are disabled by default in later versions of WordPress like 3.1 and greater so to enable them go to the post or page and look for the “Screen Options” button and select the “Custom Fields” checkbox as shown below.
Creating Custom Fields in WordPress
The next step is to add the custom field using a key and value. The meta-data is handled by key/value pairs in WordPress. To do this in WordPress all you need to do is enter a name (also known as a “Key”) and a value for the field similar to the screenshot below.
Displaying Custom Fields on your WordPress Theme
To successfully add custom fields to your WordPress theme we will need to do a couple of things first and make some additions in PHP code to display your custom field correctly.
- Using the_meta() template tag
- Working in the loop that is used to display posts in WordPress
In order to find the loop and make this change successful you need to first find the loop that controls what is displayed in the post so have a look in the index.php file’s code (you might also find this on the single.php file with certain themes)…
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
And the loop will end with the following condition…
<?php endwhile; else: ?>
<p><?php _e(‘Sorry, no posts matched your criteria.’); ?></p>
<?php endif; ?>
Now that we’ve found this let’s add the_meta() template tag to display the custom field on your WordPress theme’s post or page. As you can see in the screenshot below where you place the_meta() template tag dictates where it will show up on the front end of your WordPress theme…
So let’s look to see it on the front end in action…
Also here is what the source code looks like on the backend…
Now that you’ve seen it in action you should be good to create your own custom fields in WordPress and be able to display them on your WordPress theme with ease.