- 18 June 2018
- Content Strategy (2)
- WordPress (25)
In WordPress you can add custom fields to your posts via the post editor of your dashboard. It’s really easy to do, all you need is a name (which is constant) and a value (which can be variable). This information is stored as metadata, which you can use to display additional information on your posts such as simple text, or to trigger for more complex actions.
Uses for Custom Fields
Uses for custom fields are limitless but here are some simple examples of how they can be used to display information:
- Currently reading: Hidden Empire (Saga of the Seven Suns 1)
- Mood: Jovial
- Weather: Humid
- Rating: 9/10
- Status: Married
And some more complex examples:
- To create a list of keywords to include in your header
- To filter posts in your loop
- To list image id’s for a gallery/slideshow
- To list file id’s for a ‘related files’ section
- To create a series of posts e.g. an ‘also in this series’ list
- To add posts to a featured list of articles on your homepage
- To set a thumbnail, banner/hero image etc
Creating Custom Field Data
Firstly, you might need to add custom fields via the screen options. When editing a post, click on the screen options button at the top and make sure that custom fields are ticked:
To create a new custom field simply scroll down to the custom field options, select the ‘add custom field’ button and type in the name and value(s) you’d like to use. For this example we’re going to create a list a list of keywords, which we could use to improve the Search Engine Optimisation (SEO) of our post:
Displaying Custom Field Data in your Theme
Using an in-built WordPress function we’ll firstly get the ID of our current post. Using that, plus the name of of custom field, we can check to see if any data exists and if it does, we’ll add it to our variable ($keywords) and echo it onto the screen.
// get id of current post $id = get_the_ID(); //if our custom field has any data get it and display it if ( get_post_meta($id, 'Keywords', true) ) { $keywords = get_post_meta($id, 'Keywords', true); echo $keywords; }
You could use this code in your header.php or single.php file to add some keywords to your post’s meta data:
<!DOCTYPE html> <html> <head> <title>My web page</title> <?php //get id of current post $id = get_the_ID(); //if our custom field has any data add it to our variable if ( get_post_meta($id, 'Keywords', true) ) { $keywords = get_post_meta($id, 'Keywords', true); } ?> //display our custom filed data as meta keywords <meta name="keywords" content="<?php echo $keywords; ?>"> </head>
Comments
Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.