Wordpress allows post authors to add "custom fields" to blog posts. What this is and how this can be used "outside the loop" is the topic of this article.
Ads by Google
WordPress Custom Fields
WordPress has the ability to allow post authors to assign custom fields to a post. WordPress codex refers to this feature as “meta-data”. For example, this meta-data can include bits of information such as:
Listening To: Jazz
To explain it in plain words, everything in WordPress (as it is on the Internet, and programming in general) comes in key/value pairs. For example, the title of this post is the “key” and the value of this “key” is “WordPress Custom Fields Outside The Loop” – exactly what you see at the top of this article. The “key” can take multiple values, e.g., the key “categories” can take multiple values, like “Business, Education, Internet” etc. In actual fact, the key “posts” holds multiple values – all posts in the blog! To display multiple values, we need to use a loop – in other words, go through the list of values and display them one by one.
WordPress custom fields feature enables you to add an extra key/value pair to each blog post. For example, each blog post can have the title, body, tags, categories and a number of custom fields as discribed above (Mood, Listening To, which you will need to pre-fill with each new blog post).
WordPress: The Loop
The custom field display of value needs to be placed inside “the loop” in the WordPress template, since it needs to know what blog post it belongs to. For example, each blog post page displays the title, blog body, tags and custom field for the particular blog message. The WordPress Loop is discribed in the Codex.
Displaying Custom Fields Outside The Loop
There are times, however, when you need to display custom fields outside the loop, e.g., in the footer of the blog post. Displaying custom fields outside the loop will allow you, for example, to have a different footer for each blog post. To achieve, this two things need to be done.
1. Edit the blog post template (e.g., single.php) to make post ID available outside the loop. Find the line
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
and add the following code just below it:
<?php $GLOBALS['current_id'] = $post->ID; ?>
2. Use this code to display your custom field outside the loop, e.g., in the footer.php
<?php echo get_post_meta($GLOBALS['current_id'], "custom-field-name", true); ?>
That’s it! Now, when editing a blog post, add a custom field with “custom-field-name” and it will display wherever you put that second bit of code.
Looking For More Information?
Ads by Google
The review "WordPress Custom Fields Outside The Loop" was last updated on 18/04/2015.