As WordPress developers, we often times have clients who want the ability to add images, videos, links, or other things that appear outside of our regular templates, like in the header or footer.
As developers, it would be easy enough for us to manually include these items on certain templates or in certain places. For our clients who aren’t as WordPress or code savvy, the process is either extremely difficult or impossible.
This is where Custom Fields come into play. We allow users to enter items into a Custom Field box when adding or editing a post – which we can recall programmatically and include in our theme.
To call the contents of the a Custom Field in a theme template, we use the
get_post_meta($post_id, $key, $single);
- $post_id is the ID of the post you want the meta values for. To get the post ID of the use
$post->IDget_the_ID() within the loop.
- $key is a string containing the name of the meta value you want. Unlike other facets of WordPress, we don’t use the slug here, we use the full string including spaces and special characters.
- $single can either be true or false. True will return a single result. False, or not set, will return an array of the custom fields.
Let’s say that you have a Custom Field on your blog pages that you want your client to use to enter a custom banner image. You could build your template to have the Featured Image field to be used for this, but most bloggers want to be able to use the Featured Image field to add an image that can be incorporated into the full post, the post excerpt and even the RSS feed. In situations like this, I turn to Custom Fields. For this example, we’ll name the custom field “Banner Image”. For the sake of simplicity, lets say that this field will be used by the client to enter an image location of an image uploaded to Flickr. They paste the image URL in the Custom Field, and we use the below function to recall it in our template file.
get_post_meta($post->ID, 'Banner Image', true);
We can now store this in a variable, and place it wherever we want.
I hope my simplistic example is helpful. If you have any questions, or more complex examples, please leave a comment below.