Displaying Custom Field Data in WordPress

Custom fields can be very powerful and add a lot of flexibility to your content. Learn how to create custom field data and display it in your WordPress theme.

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:

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:

Screen options in WordPress

Screen options in WordPress

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:

Custom field options in WordPress

Custom field options in WordPress

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

We welcome comments! Please read the disclaimer.