DiggingIntoWordPress

by Chris Coyier & Jeff Starr

Global Custom Fields

Posted by on

UPDATE: Make sure to take out “Take Two” on this concept, with a cleaner method for doing this.

Custom fields allow us to attach data to Posts or Pages that we can yank out and use at will in our templates. They are awesomely flexible and single-handedly allow WordPress to be used for about any CMS need. The fact that they can only be used on single Posts can be limiting in some circumstances. Sometimes you wish you could grab a custom value that you can control and is consistent globally, regardless of the current post. In this post we’ll look at a technique to do so.

Fair Warning

This might not be the perfect technique. If you read this and have a smarter way, I’m all ears, this worked for me in my quick testing. What would really be slick is to make a plugin out of this, where you can create global key/value pairs through a special settings panel that could be use anywhere.

WordPress already has a somewhat-similar system in place through how the bloginfo function works.

<?php bloginfo('name'); ?>

Perhaps that could be tapped into and expanded upon, I dunno.

Example Use

One idea is for something like an Amazon affiliate ID code. You might use a value like this all over the place on a site, embedding within amazon links and widgets. If you hard-code this value, and then need to change it someday, that would suck. It would be better to save this value in one place, and use a variable (global custom field) to output it.

1. Create a Page

Call it “Global Custom Fields”. It doesn’t need any content, but you can use this page to add the custom fields you wish to use globally.

Notice down below, we just add custom fields in key/value pairs like any other custom fields on any other Page or Post.

Make sure to note the ID of this Page. We’ll need that ID for the custom functions we are about to write, but you can also use it to exclude this page from any dynamic navigation and such, as it’s not really meant for public viewage.

2. Create Generic Function

The built-in WordPress get_post_meta function accepts any Post ID and any key value. So we’ll add a new function to our theme’s functions.php file that generically returns values for keys we pass it. The Page ID will be hard-coded, equal to the value we just noted down.

function global_custom_field($key) {
   $output = get_post_meta(677, $key, true);
   echo $output;
}

3. Create a Shortcode Function

With our generic function, we can already use it just as-is in our templates. Without a special plugin though, you can’t execute PHP functions in the body of articles though. We can be even smarter though, and create a shortcode function for use in our content.

More stuff for your functions.php file:

function gcf_func($atts) {
    extract(shortcode_atts(array(
		'key' => 'amazon_id'  // default value if none supplied
    ), $atts));
    return global_custom_field($key);
}
add_shortcode('global_custom_field', 'gcf_func');

4. Use it!

Now anywhere in our template we wish to call in the value of a global custom field, we just pass the function the key value and we get back our value:

echo global_custom_field("amazon_id");

Or right inside our posts content:

[global_custom_field key="amazon_id"]

12 Responses

  1. Nice! Great way to make a config-kinda-thing!

  2. A plugin of quick tags would be wonderful, where you could simply define a reference and a value and use it with curly brackets perhaps, smarty style.

    {amazon_id}. Done.

    I wonder how much scope there is for this?

  3. lumpysimon September 16, 2009

    Hi Chris

    I can see what you’re trying to achieve and it’s could be useful when you quickly need something like this, but my nerdy programmer side is saying “I don’t like it at all!” – Putting a global option within a page seems very unintuitive and semantically wrong. In order to change the value of the option, you would have to go to ‘Edit Pages’, find the correct page, edit the custom field, save the page, etc.

    Personally I would create a new simple admin screen to go under the Settings menu, with an input field that stores the value in an option in the WordPress database.

    It’s probably about 10-15 more lines of code, but much more usable, changeable, future-proof and ‘correct’ in terms of using the inbuilt structure that WordPress provides.

    • I totally agree. You should write that up, or better yet, make a plugin! I fully admit this is a somewhat hacky solution. That’s what you get sometimes when a designer like me has to come up with development solutions fast.

      I’d be happy to link to a better solution elsewhere, or I’d be open to a guest post.

    • I would love to see this solution done. Been thinking about doing this for loop exclusions, so that I can add different Post Types (categories) but not have to change every loop instance. But I can see how this would be very useful for a number of different values.

  4. The general idea is really good.
    Why not use a config file and define constants there? At least we can do that for our very own purpose (it may be hard for clients to do that).
    We could easily hook up to wordpress settings page and add our own key pairs there. It seems more semantic to me.
    Thanks for sharing Chris!

  5. Can’t you add your own stuff to the options table and then pull it out with get_option()?

    I’ve never tried it but I think that’s the proper way.

  6. There already exists the plugin Pods CMS for WordPress, which I use all the time. It’s extremely customizable and easy to use. The Pods you create, or data objects can have multiple columns of data and can even be related to each other. And they are completely separate from specific pages/posts allowing them to be truly global.

  7. Hey everybody, I wrote a plugin for wordpress global variables after reading this.

    You can add variables, name them and give them a value.

    You can then get an array of the values and use them anywhere in your code by using the name of the variable. For example:

    As a global variable you add ‘FirstName’ with a value of ‘Liam’.

    Within your theme you can grab the array by calling getGlobalVars():

    $vars = getGlobalVars();

    You can then access the variable via the name you specified:

    echo “First Name: ” . $vars['FirstName'];

    :D would anybody be interested in using/reviewing it?

    - Liam Goodacre

    • I think it looks like you’ve made good progress, and now you should perhaps look at some sort of tag replacement method so that a user could use a shortcode (not necessarily one in square brackets, but something easier – maybe curly brackets like {FirstName}) to return their variable.

      Then lots of people would use it ;)

    • Would love to see this as a plugin. Where can I find it? Id be happy to review it

Comments are closed. Contact us with any critical information. Thank you!

Code is poetry