About The Author

Alex Denning is a WordPress developer from London, England. He sells WordPress themes and writes about WordPress . More about Alex

Extend WordPress With Custom Fields

Quick Summary

WordPress’ popularity has grown exponentially as of late. This rise in popularity is due in part to WordPress’ custom fields. Custom fields allow you to add little bits of data to posts. They have changed the way people look at WordPress. A couple of years ago, WordPress was a blogging platform — a good one, but a blogging platform nonetheless. Now it’s widely considered to be an excellent simple content management system. How did it evolve so quickly? Custom fields, that’s how. How exactly did these bits of data transform WordPress? The fields could initially include the weather — as the codex points out — the temperature and various other not-particularly-useful things. And that was the story for a while. Then people started to realize that they could use the custom fields to store URLs of images. They could then pull these images to the home page to create magazine-style layouts. These magazine themes, as they became known, evolved, and eventually you were able to pull images automatically from posts. You can draw a direct line from WordPress’ popularity to the magazine themes to custom fields.

Table of Contents
Membership counter

Members support Smashing

Wonderful, friendly people who keep this lil' site alive — and get smarter every day.

Are you smashing, too? →

WordPress’ popularity has grown exponentially as of late. This rise in popularity is due in part to WordPress’ custom fields. Custom fields allow you to add little bits of data to posts. They have changed the way people look at WordPress. A couple of years ago, WordPress was a blogging platform — a good one, but a blogging platform nonetheless. Now it’s widely considered to be an excellent simple content management system. How did it evolve so quickly? Custom fields, that’s how.

How exactly did these bits of data transform WordPress? The fields could initially include the weather — as the codex points out — the temperature and various other not-particularly-useful things. And that was the story for a while. Then people started to realize that they could use the custom fields to store URLs of images. They could then pull these images to the home page to create magazine-style layouts. These magazine themes, as they became known, evolved, and eventually you were able to pull images automatically from posts. You can draw a direct line from WordPress’ popularity to the magazine themes to custom fields.

You may also want to check out the following Smashing Magazine articles:

The Custom Field Syntax

custom-fields

In order to do more complicated things, you’ll need to understand the syntax. Creating a custom field is easy: it requires a name and a value. The name is constant, but the value can change with each post.

A real-world example: let’s say you run a blog about cameras. You have categories set up for each type of post (“Review,” “New,” etc.), and you tag the post with the manufacturer’s name. But you want to display the price and specifications of the camera. This is as easy as creating a new custom field with the name Camera_Specs and then typing the info into the value box. Click the “Add” button and you will have added the custom field to the post.

Displaying the field on the page is simple, too. In the single.php file, add the following code:

<?php echo get_post_meta($post->ID, "Camera_Specs", true); ?>

(You might want to wrap this in a paragraph, ordered list or the like. You can use HTML in the value of the field.)

Custom fields can be conditional, too. We can display a camera’s specs or, if that isn’t available, some generic text.

<?php $camera_specs = get_post_meta($post->ID, 'Camera_Specs', true);
if ($camera_specs) {
?>
<?php echo $camera_specs; ?>

<?php } else { ?>

<p>No specification available.</p>

<?php } ?>

That’s the general syntax, and now the only limit is your imagination!

Spicing Up Post Titles

custom-fields-title

Post titles are usually fairly boring. You’re limited to text. Links aren’t possible, nor is HTML. Well, not anymore. Custom fields to the rescue!

Using a conditional statement and custom fields, adding any HTML to your posts’ titles is now possible. (This won’t work with RSS feeds or the like, but it works great for any titles on the blog itself.) We’ll use the custom field Post-Title:

custom-fields-post-title

You can add any HTML you like to your posts’ titles. Implementing it on your blog is easy, too. You’ll have to use the following code on all pages on which titles are displayed: the home page, archives, current posts, etc. The following snippet looks for the custom field and falls back on the_title:

<?php $post_title = get_post_meta($post->ID, 'Post-Title', true);
if ($post_title) {
?>
<h2><?php echo $post_title; ?></h2>

<?php } else { ?>

<h2><?php the_title(); ?></h2>

<?php } ?>

An easy yet effective way to improve your website.

Only Display Posts With A Specific Custom Field

WordPress displays posts through something called a loop. Another WordPress function, query_posts, allows you to choose exactly which posts are displayed in your loop. One parameter lets you display only posts that have a custom field and/or that have a specific custom field value. Going back to our camera website, we could display only posts that have the custom field Camera_Specs:

query_posts('meta_key=Camera_Specs');

If we wanted to display only cameras that had 10 megapixels (and if all posts had the custom field Camera_Specs_Pixels that specified the value of the number of megapixels), we could do so with the following:

query_posts('meta_key=Camera_Specs_Pixels&meta_value=10');

You may want to do this on a custom page template. If so, just add the following to the top of the file and name it appropriately (e.g. camera-specs-pixels.php):

<?php /*Template Name: Camera Specs Pixels */?>

To make your new page template show up, create a new page, and then in the drop-down on the right, choose the page template you’ve just created. Publish the post, and you’re done!

Using Custom Fields To Create A Unique Design

WordPress 2.7 introduced the post_class function. This allows you to apply specific CSS classes to posts (thus giving them unique designs). Guess what? You can use custom fields to apply particular classes!

This one is a bit more involved. First, open your functions.php file and add the following code:

function shiftnews_post_class($classes) {
   global $post;
   $sn_post_class_array = array (
      get_the_author_meta('display_name'),
      get_post_meta($post->ID, 'post-class', true)
   );
   $classes[] = implode(" ", $sn_post_class_array);
   return $classes;
}

You’ll then need to edit your single.php file, adding <?php post_class(shiftnews_post_class()); ?> to a DIV that wraps your content. Using the custom field post-class, you can then type in CSS classes (e.g. flower-bg or blue-content, which would apply the classes .flower-bg or .blue-content), thus adding them to the post.

The possibilities here are inspiring, and this is quite possibly the best way to create a unique post design for WordPress.

Set a different background for each post with custom fields

Screenshot

You could take this even further by allowing users to choose a background image through custom fields. Of course, you could just resize the image to 1920x1200, upload it and copy the URL into a custom field, ‘background’ and then put the following code in your header:

<?php if (is_page() || is_single()) {

<?php $background = get_post_meta($post->ID, 'background', true);
if ($background) {
?>
<style type="text/css">body{ url(<?php echo $background; ?>) no-repeat fixed; }</style>

<?php }
}?>

But that would be a pain to do every single time you just wanted to change the background image. There is an easy way to do it: upload an image, copy the URL into a custom field and then use a script to resize the image and set it as the background.

First thing to do is to upload an image. We’re going to be resizing it to 1920px (although depending on your audience you may want to use a higher/lower resolution) so anything that’s 1200px wide or above should look fine.

Copy the relative URL of the image (ie /wp-content/… , not http://yoursite.com/wp-content/) into a custom field called ‘background’ and click ‘add custom field’. Next, we need something to resize the images with. We’ll be using timthumb. Upload it to /yourtheme/timthumb/ and we’re ready to go!

Open up your header once again and add (below your theme’s stylesheet) the following:

<?php if (is_page() || is_single()) {

<?php $background = get_post_meta($post->ID, 'background', true);
if ($background) {
?>
<style type="text/css">background: url(<?php bloginfo('template_url'); ?>/timthumb/timthumb.php?w=1920&zc=1&src=<?php echo $background; ?>) fixed no-repeat;</style>

<?php }
}?>

What that does is takes the image from the custom field and then runs it through timthumb so it gets resized to fill the entire screen, even on large monitors (the image then gets cached, so it is only generated once). The resized image is then displayed as the background of the post.

If you’re having problems, make sure you’ve got the relative URL and not the absolute URL of the image, it is hosted on your server (you’re not hotlinking!) and that you have the file permissions set correctly (as shown in the timthumb wiki). This is one of my favourite things to do with custom fields as not only is it easy to do, but it’s also very effective in differentiating different blog posts; this technique is used to great effect on Nometet.com.

Search Engine Optimization With Custom Fields

The “All in One SEO Pack” is consistently one of the most popular plug-ins for WordPress. It allows you to do things like specify your own title tag or meta description. It is powered by custom fields, meaning you can recreate it in your theme.

Start by adding the following code to your theme’s title tag:

<?php if ( is_single() || is_page() ) { ?><?php $title = get_post_meta($post->ID, 'Title', true);  if ($title) { ?>
<?php echo $title; ?> | <?php bloginfo('name'); ?>
<?php } else { ?>
<?php wp_title(''); ?> | <?php bloginfo('name'); ?>
<?php } ?>
<?php } ?>

Now, when a page or post is displayed, WordPress will look for the custom field Title. If it exists, its contents will be displayed; if it doesn’t, then the post’s title will be displayed. To use this new-found power, create the custom field Title and make its value what you want to be displayed in the title tag (note that | [Blog name] will be added).

You can apply the same idea to other elements, such as the description tag:

<?php if (is_single() || is_page() ) : if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<meta name="description" content="<?php $description = get_post_meta($post->ID, 'Description', true);  if ($description) { ?><?php echo get_post_meta($post->ID, "Description", true); ?>
<?php } else { ?><?php the_excerpt_rss(); ?><?php } ?>" />
<?php endwhile; endif; elseif(is_home()) : ?>
<meta name="description" content="<?php bloginfo('description'); ?>" />
<?php endif; ?>

The code above should replace the entire description tag and allow you to use the custom field Description to display the contents of the description tag. If the custom field does not exist, then the excerpt is used on posts and pages, and the blog’s description (which you set when you installed WordPress) is used on the home page.

Read more on the topic in the article WordPress SEO: The Definitive Guide To Higher Rankings For Your Blog.

Custom This, Custom That!

Custom fields are very powerful, and the only limit is your imagination! As we’ve seen in this post, you can do some really awesome things with WordPress’ custom fields. They can improve both your blog and its ranking in search engines. Enjoy!

If you’d like to do some further reading:

The possibilities for this are inspiring, and this is quite possibly the best way to create a unique post design for WordPress.

Of course, the other option is to use custom fields to include a style sheet that is specific to the post or even just to use inline styling.

You can add a style sheet to a post with a custom field value quite easily. First, add the following code to the header.php file, after your theme’s style sheet loads:

<?php if (is_page() || is_single()) {

<?php $stylesheet = get_post_meta($post->ID, 'Stylesheet', true);
if ($stylesheet) {
?>
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?><?php echo $stylesheet; ?>.css" type="text/css" media="screen,projection,tv" /></h2>

<?php }
}?>

This tells WordPress to look for the custom field Stylesheet on posts and pages. All you’ve got to do is enter the name of the style sheet (so if it’s blue.css, just enter the value blue) and upload it to your theme’s directory.

A whole new style sheet might be overkill in some cases, though. If you’re changing just one or two styles, then inline styling might be the way to go. This is just as easy: paste the following code into your header.php file, again after your theme’s style sheet loads:

<?php if (is_page() || is_single()) {

<?php $styles = get_post_meta($post->ID, 'Styles', true);
if ($styles) {
?>
<style type="text/css"><?php echo $styles; ?></style>

<?php }
}?>

This piece of code looks for the custom field Styles; put in it any styling you want to apply only to that post. For example:

body{
    color:#000;
    background:#fff;
}

There’s something for everyone here, so you can start to quickly create unique post designs however you prefer! You might want to look at Smashing Magazine’s previous post about custom fields as well.

Smashing Editorial (al)