Adding custom post classes in WordPress


Whoa there!

This post contains code that's more than 12 years old. It might be fine, but you should probably check to make sure this isn't incredibly stupid by today's standards.

Here’s my first attempt at writing something useful on this site. Don’t hate me if this has been said before on a million other sites.

The WordPress post_class() function normally spits out a bunch of semi-useful classes by default, but unless you want to have to use classes like .post-734 in your stylesheet, sometimes you need to go a step further.

Over at Digging into WordPress, Chris Coyier has an easy tip on how to add custom classes to post_class().

As it turns out, it’s trivial to add a custom class to a post. Here’s all you have to do:

<?php post_class('classname'); ?>

That’s pretty self explanatory, but you’ve still got to hard-code that class into your template. What if you want to change it on a per-post basis? Well that’s easy: Just use a custom field. Here’s how:

Step 1

Create your custom field. Let’s use “custom_class” as our name and “fancy” as the value.

WordPress custom field screen

Step 2

Set the value of the custom field as a variable inside your loop.

<?php if (have_posts()) : ?>
	<?php while (have_posts()) : the_post(); ?>
		<?php $custom_classes = get_post_meta($post->ID, 'custom_class', false);  ?>

Step 3

Now, let’s use that variable in post_class(), instead of the hard-coded value we saw earlier:

<article <?php post_class($custom_classes) ?> id="post-<?php the_ID(); ?>">

That’s it. You can use the same custom field multiple times in a single post. The false you see above means it will return an array of values, so if you’ve got ten “custom_class” custom field values, you’ll get all ten as custom fields in that post.

Custom field generated code

This simple technique is already in use on this site, and it will allow me to eliminate a plugin on this year’s redesign of The Yule Blog.

I’ve created a gist on GitHub, so go fork it or comment there, if that’s your thing.