Post Pic

WordPress: How to get custom fields outside the loop

Custom fields are definitely very useful and are used on many WordPress-powered blogs. In this recipe, I’m going to show you how to easily get custom fields values outside the loop.

To display a custom field value outside the loop, simply use the following code. Don't forget to replace customField on line 4 by the name of the custom field you want to display.

<?php 
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'customField', true);
?>

Thanks to Paul Whitehead for contributing to WpRecipe with this nice trick! If you'd like to share your WordPress knowledge with the community, don't hesitate to contribute.

6 Responses

Jul 28 2012 19:38

Ok,
Here’s what I’m trying to do:

Create a page called “Custom Fields” that will never actually be seen by a user. It’s simply for the client to add in custom fields. He will constantly be needing to change these custom fields on a weekly/monthly basis.

I need these custom fields to be displayed inside the header, footer, or sidebars.

Do you know the proper way to tweak the code so I can achieve this?

Thanks!

Sep 11 2012 08:36

@Justin: Came across this while looking for something else but I saw your question. I’m not entirely sure what you mean by creating a “Custom Fields” page, but I immediately thought of the Custom Fields Template plugin.

Perhaps this will help? http://wordpress.org/extend/plugins/custom-field-template/

Good luck – Brian

Sep 12 2012 20:50

Thanks for this! Works great!

Nov 24 2012 00:08

Hey Justin,

I think what you#re actually trying to achieve is a theme-options page. custom fields are always related to posts, so a custom-fields “page” in your admin panel, wouldn’t make any sense.

I stumbled upon a template for this today. Maybe it will be helpful to you, although you might have found your answer already by now. Have a look at this Template: http://themeshaper.com/2010/06/03/sample-theme-options/

With this you can easily define theme option fields and display or use them anywhere on your page.

Hope that helped a little!

– Steven

Nov 24 2012 00:10

Oh, and thanks for this article. I always have to google this, and I always end up here. ;)

May 14 2013 13:22

Thanks for this mate..cheers

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox