WordPress Custom Fields Tutorial

WordPress custom fields provide an easy way to add extra data to various places in your themes. There are many ways that custom fields can be used, one of the more common ways being to set up single key/value pairs to use in your theme, which is what I will demonstrate in this WordPress custom fields tutorial.

Page Setup

When you are editing a page, there should be a section underneath the main editor called “Custom Fields”. In this section, you can add custom metadata to your post. All you have to do is provide a name to identify your extra information, as well as the information itself.

For example, lets say you wanted to add a section to a page for your favorite book, The Cat in the Hat. To accomplish this, you could add a custom field called ‘book’ with the value ‘The Cat in the Hat’.
ss1

Theme Setup

To get this information to show up on your site, you have to edit your theme and use the WordPress function get_post_meta(). Take a look at the following snippet of code:

 

<?php
echo esc_html(get_post_meta(get_the_ID(), ‘book’, true));
?>

 

The get_post_meta function takes up to three parameters. The first it requires is the post id. We get this using the function get_the_ID() above. The next required piece of information is the key we stored our value under, in this case ‘book’. The last parameter tells WordPress we want a single value back, rather than an array.

The above snippet would output ‘The Cat in the Hat’ to the page.

More Custom Fields

You can always use more than just one key/value pair. Extending the above example, you could also create another custom field for the author of your favorite book. Just create a custom field with the key ‘author’ and the value ‘Dr. Seuss’. You would use a similar snippet of code to retrieve the author, just change the second parameter of get_post_meta from ‘book’ to ‘author’

Next, see part 2 of this tutorial