Example uses of custom fields in WordPress

In the previous article I showed how to create Custom Fields, and how to use them. I won’t go into the creating part anymore, since you could read that in the last article.

Let’s focus on styling.

Suppose you wanted different colors on different posts in home page, how would you do that?

The answer is simple: Custom Fields. If we created a Custom Field called post_color (I’m always reluctant to use blanks in Custom Field names, but I suppose it’s alright), and assigned a color per post (like red, green, black), then we’re ready to rumble.

In modern themes, posts are given a default set of css classes by using the post_class() function. This function can be expanded by giving it our own classes as parameter.

< ?php while (have_posts()) : the_post(); ?>
 
< ?php
  $postcolor=get_post_meta($post->ID, 'post_color', true);
?>
 
<div <?php post_class($postcolor) ?> id="post-< ?php the_ID(); ?>">
 
</div>

In this example we extract the Custom Field post_color from the post (just one) and pass the value to post_class().

I you now reload your site, another class has been assigned to each and every post where you added the Custom Field to.

This class can then be used in your stylesheet (style.css) to add extra properties to the particular post, like

.red {
  background-color: #f00;
  color: #fff;
}

This example will give a red background, and white foreground colors.
(I know, it’s an ugly example, but it fits the purposes).

Now create every possible color combination you can imagine, and add them to your posts :-)

Suppose you wanted to decide per post if you wanted a sidebar or not (and also: which sidebar if you have more than one), this is also possible with Custom Fields.

Lets start at the beginning, by defining two additional sidebars for widgets (I’m still working on the default theme).

< ?php
 
if ( function_exists('register_sidebar') ) {
        register_sidebar(array(
                'before_widget' => '<li id="%1$s" class="widget %2$s">',
                'after_widget' => '</li>',
                'before_title' => '<h2 class="widgettitle">',
                'after_title' => '</h2>',
        ));
}
 
if ( function_exists('register_sidebar') ) {
        register_sidebar(array(
                'before_widget' => '<li id="%1$s" class="widget %2$s">',
                'after_widget' => '</li>',
                'before_title' => '<h2 class="widgettitle">',
                'after_title' => '</h2>',
        ));
}
 
if ( function_exists('register_sidebar') ) {
        register_sidebar(array(
                'before_widget' => '<li id="%1$s" class="widget %2$s">',
                'after_widget' => '</li>',
                'before_title' => '<h2 class="widgettitle">',
                'after_title' => '</h2>',
        ));
}
 
?>

When this is in your functions.php (in your theme directory), and browse to your widget page in the appearance section of your administration backend, then you’ll see three sidebars, numbered 1 to 3. Just drag some widgets to all of them, preferably different ones, to make use of them in this example. The above snippet is just the part that is needed to create 3 widgetized sidebars, there might be more code already in your functions.php.

The way we are going to call these different sidebars from the theme is by using the dynamic_sidebar() function. This function takes one parameter: the number (or if you defined it, its name) of the sidebar, and defaults to 1. So we could call it with dynamic_sidebar(3), and it’ll show the third sidebar we just filled with some widgets.

Now modify three posts and add a Custom Field to each, called ‘sidebar’, their values should be 1, 2 and 3 (just to keep it simple). Make sure you have a fourth post without the sidebar Custom Field.

The next part to focus on is the single.php file. Do not alter your index.php to reflect the changes below, since it could have some strange effects. Remember that Custom Fields are part of a post, and when displaying 5 posts on your index.php file, it’s kinda strange if you try to change the sidebar 5 times. I’m actually not sure what would happen, probably the last post on the page is chosen as sidebar, but I’m not going to try. You’re welcome to try (and report back), but I’m certainly not promoting this: do at your own risk!

Let’s describe what’s going to happen in single.php: upon querying the database for the post (and its Custom Field), we have to decide whether the post gets a sidebar or not. Depending on this we have to style our page differently. In the Default theme, the difference between the both are two classes named narrowcolumn (page with sidebar) and widecolumn (page without sidebar). If the sidebar is in the page, also a div called sidebar is visible.

So lets have a look at the single.php (I’m going to strip it a bit, for readability):

< ?php
/**
 * @package WordPress
 * @subpackage Default_Theme
 */
 
get_header();
?>
  <div id="content" class="widecolumn" role="main">
  < ?php if (have_posts()) : while (have_posts()) : the_post(); ?>
 
      <div <?php post_class() ?> id="post-< ?php the_ID(); ?>">
           <h2>< ?php the_title(); ?></h2>
 
           <div class="entry">
               < ?php the_content('<p class="serif">Read the rest of this entry &raquo;'); ?>
           </div>
      </div>
 
      < ?php comments_template(); ?>
 
   < ?php endwhile; else: ?>
 
       <p>Sorry, no posts matched your criteria.</p>
 
< ?php endif; ?>
 
    </div>
 
< ?php get_footer(); ?>

There’s already one minor problem here: the part where the layout is decided (‘widecolumn’ vs ‘narrowcolumn’) is outside the loop, so we have to move that part inside the loop. Also are we going to query the post for the Custom Field ‘sidebar’ (just one, it wouldn’t make sense to have more than one sidebar Custom Field in our setup, but it could be if you have multiple sidebars in your posts).

< ?php
/**
 * @package WordPress
 * @subpackage Default_Theme
 */
 
get_header();
?>
 
  < ?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    < ?php
      $sidebar=get_post_meta($post->ID, ‘sidebar’, true);
      if ($sidebar) 
        $columnclass='narrowcolumn';
      else
        $columnclass='widecolumn';
 
    ?>
    <div id="content" class="<?php echo $columnclass; ?>" role="main">
 
      <div <?php post_class() ?> id="post-< ?php the_ID(); ?>">
           <h2>< ?php the_title(); ?></h2>
 
           <div class="entry">
               < ?php the_content('<p class="serif">Read the rest of this entry &raquo;'); ?>
           </div>
      </div>
 
      < ?php comments_template(); ?>
 
   < ?php endwhile; else: ?>
 
       <p>Sorry, no posts matched your criteria.</p>
 
< ?php endif; ?>
 
    </div>
 
< ?php get_footer(); ?>

Again this coding gives some styling problems: the post(s) (plural, because that’s how the loop works) need to be inside the content div, but it gets called more often than it should be. Therefore the background goes haywire, but for our purposes it suffices. What needs to be done to make it clean, but outside the scope of this article, is to differentiate between the content (posts and the sidebar), and the individual columns (left column and sidebar). Content (and sidebar) are then outside the loop, while the left column (including the narrowcolumn/widecolumn class) is inside the loop. Please ignore the vanishing background for now.

*EDIT*: it seems I’m the only one having this problem with one of my Firefoxes.

What here happens is that the post is queried for the Custom Field ‘sidebar’ (nothing new here), and based on its existence $columnclass is set to either ‘narrowcolumn’ (with sidebar) or ‘widecolumn’ (no sidebar). You can already see the difference between posts with the ‘sidebar’ Custom Fields, and those without.

Now we need to have the actual sidebar display:

< ?php
/**
 * @package WordPress
 * @subpackage Default_Theme
 */
 
get_header();
?>
 
  < ?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    < ?php
      $sidebar=get_post_meta($post->ID, ‘sidebar’, true);
      if ($sidebar) 
        $columnclass='narrowcolumn';
      else
        $columnclass='widecolumn';
 
    ?>
    <div id="content" class="<?php echo $columnclass; ?>" role="main">
 
      <div <?php post_class() ?> id="post-< ?php the_ID(); ?>">
           <h2>< ?php the_title(); ?></h2>
 
           <div class="entry">
               < ?php the_content('<p class="serif">Read the rest of this entry &raquo;'); ?>
           </div>
      </div>
 
      < ?php comments_template(); ?>
 
   < ?php endwhile; else: ?>
 
       <p>Sorry, no posts matched your criteria.</p>
 
< ?php endif; ?>
 
    </div>
 
  < ?php
    if ($sidebar)
  ?>
    <div id="sidebar" role="complementary">
      <ul>
        < ?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar((int)$sidebar) ) : ?>
      </ul>
    </div>
  < ?php
    endif;
  ?>
 
< ?php get_footer(); ?>

What happens here: if the variable $sidebar exists (i.e. contains a value) when we collected it from the post, and when the function ‘dynamic_sidebar’ exists, then call it and use the sidebar number as its parameter. Since all variables in PHP are treated as strings, dynamic_sidebar() doesn’t recognize our input without special treatment, since we decided to use numbers (which is implicit when not giving names to sidebars). Therefore the variable $sidebar is typecasted to an integer (int).

If you created the three sidebars, and gave the Custom Field ‘sidebar’ a number between 1 and 3, then that sidebar will appear in your post. If you gave it a number higher than 3 (while only having 3 sidebars), then the layout will create the space for a sidebar, but no sidebar will show up.

Having the freedom to decide on whether a sidebar should appear, and even the freedom which sidebar should appear, gives a whole lot of powerful options to WordPress.

That’s it for now. I hope you enjoyed this article.

This entry was posted on Tuesday, October 6th, 2009 at 10:17 pm and is filed under webpublishing. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Comments to Example uses of custom fields in WordPress

  • [...] A ‘warning’ up front (just to let you enjoy the power of WordPress): I’m going to create some pages, attach Page Templates to them, and going to use Custom Fields as well. You might want to read up on Custom Fields in my previous articles (”Using custom fields in WordPress posts” and “Example uses of custom fields in WordPress“). [...]

  • [...] more from the original source: Example uses of custom fields in WordPress | boosten.org Tags: customfield, [...]

  • Leave a Reply

    Spam Protection by WP-SpamFree