WordPress Custom Fields: Listing A Series Of Posts

Do you write long series of posts? Do you have a bunch of articles that definitely need to be linked together? This WordPress custom fields technique will allow you to do that without a lot of hassle. Basically, this is a simple, customized related posts script. It checks to see whether a post is in a series, then lists all the posts in the series.

The WordPress custom fields tutorial series uses this code for listing posts. You can scroll to the bottom of this entry to see what the outcome looks like.

The reason I’m writing this tutorial is precisely because of the WordPress custom fields series. After three posts, and going back to each previous post to add a link to the new post, I realized that this was only going to get more tedious and time-consuming each time I wrote another article in the series. So, this idea was born from that.

Set up your posts:

The first thing you will need is at least two posts. You need to create a Key named “Series Name” and assign it to each post. You also need to come up with an actual name for this series, then put that in the Value box. The Key and Value need to be the same for each post. Otherwise, this won’t work.

Modify the code:

Now, open “single.php” from your theme directory. Scroll to the bottom and find the closing </div> that ends the post. This will be different with individual themes. You can place this wherever you like. My code is after the post and before the comments template.

Insert this code:

<?php // Checks to see if the post is in a series

// Get Series Name
$series_name = get_post_meta($post->ID, 'Series Name', $single = true);

// If post is in a series
if($series_name !== '') {
	// Echo the list header
	echo '<h3>Other articles in the ' . $series_name . ' series:</h3>';

Basically, this checks to see if your article is in a series at all. If it is, a header for your list is displayed. If it’s not, then the rest of the code won’t run.

Now, we need to query the database for posts specifically with the same series name as this post. We do this by narrowing the query down to the post meta Key and post meta Value.

	// Query the database for the posts
	$query_string = "
	SELECT *
	FROM $wpdb->posts
	LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
	WHERE $wpdb->postmeta.meta_key = 'Series Name'
	AND $wpdb->postmeta.meta_value = '$series_name'
	AND $wpdb->posts.post_status = 'publish'
	AND $wpdb->posts.post_type = 'post'
	ORDER BY $wpdb->posts.post_date ASC
	";

All that’s left to do now is output the posts in a nice, neat list. I’m currently using an unordered list (<ul>), but you can easily change this to an ordered list (<ol>). Add this last bit of code and you’re done.

	// List the posts
	$series_posts = $wpdb->get_results($query_string, OBJECT);
		if ($series_posts):
		echo '<ul>';
		foreach ($series_posts as $post):
			echo '<li>'; ?>
			<a href="<?php echo the_permalink(); ?>" title="<?php echo the_title(); ?>">
			<?php echo the_title();
			echo '</a></li>';
		endforeach;
		echo '</ul>';
		endif;
		rewind_posts();
	} // End check for series
?>

This is a little more complicated than some of our other scripts in the Wordpress custom field series because of the database query. If you noticed, I changed a little something with the naming of the Key in this post of the series. Do you know what it is?

I capitalized the name and used a space between the words: “Series Name.” In the previous posts, this would have looked like “series-name.” The reason I changed, was to show you a different way to name your Keys. You should note that custom field Keys are case-sensitive.

What if I use a related entries plugin?

I use a related posts plugin on this site, and this is quite useless when I’m customizing my related posts with this method. I’m going to fix this little problem by using a PHP “else” statement.

So, if this post is in a series, my related posts are replaced by my list of the posts in the series. The related posts plugin is used if the post is not in a series.

<?php
else {
	if(function_exists('related_posts')) { ?>
		<h3>Related Posts</h3>
		<ul>
			<?php related_posts(); ?>
		</ul>
		<?php }
	} // end else ?>

Custom post titles in the list:

If you want to add custom titles to individual articles specifically for this list, you can create a Key named “Series Article” and give it a Value of “Your Custom Title.” This might be useful if your titles are something like “Example Series: Bla Bla Bla” and “Example Series: Yada Yada Yada.” You may want to remove the “Example Series” part because your readers will already know what series of articles this is.

In the above code, replace the code between the “foreach” and “endforeach” with this:

// get article titles
$series_article = get_post_meta($post->ID, 'Series Article', $single = true);
echo '<li>'; ?>
<a href="<?php echo the_permalink(); ?>" title="<?php echo the_title(); ?>">
<?php if($series_article !== '') echo $series_article; else echo the_title();
echo '</a></li>';

Final thoughts:

Now, that should do it. You can always tweak this script to better apply to your needs. There are also some other uses you can extract from this article. The database query of a custom fields Key and Value is useful, and I’ll definitely use it in later posts in this series.

I’m already loving this because I won’t have to go back to the previous three posts in this series just to link back to this article. Life is much simpler now.

As always, remember to subscribe to the feed to stay updated on the WordPress custom fields tutorial series. I have a few more ideas up my sleeve and am ready to post them as soon as I finish testing.

Let me know if you liked this tutorial. I’m always open to feedback and looking for new ideas to implement.

10 Responses to “WordPress Custom Fields: Listing A Series Of Posts”

  1. Or, you could just use the In Series plugin instead. Benefits include a pretty UI for adding posts to a series, automatic link insertion (no theme hacking required), and no PHP skills needed. Give it a try, I’m sure you’ll love it. :)

  2. Thanks Quandary for stopping by. While I’m sure the plugin is great, this tutorial series isn’t really about the specific things I cover. It’s about learning to use custom fields.

    The main goal here is to play with different ways to display content and extend WordPress. This sometimes means not having to find just the right plugin for your needs.

    I much prefer writing the code myself as opposed to using a plugin. One reason is because some plugin authors eventually stop supporting their plugins (this is not to say that you’ll do this). Eventually, I turn these “hacks” into plugins for use on my site, and sometimes release them to the public.

    Mostly, this tutorial series is about allowing others to learn the system. If we all use plugins for everything, then who’ll be the next generation of plugin developers?

  3. If we all write our own, how will we get anything else done? How will the people who can’t write their own ever find one that does everything they need, instead of what the developers need? And if you maintain everything yourself anyway, how is it a loss to pick up an already working, already supported plugin — even if the developer keels over dead the day after you install it? ;)
    I understand what you’re saying here. However, consider how I found this page: I was checking up on search engine keyword rankings, and this post kept coming up over, over, and over again as a contender with the likes of Organize Series, In Series, and articles describing how to implement series with these plugins. In that context, this is very much a “check out this solution” post. In the context of “learning how to use custom fields,” it’s a functional, topical toy. My main interest here is to highlight the latter over the former, because there are much more complete solutions available (and I may have happened to invested a few hundred hours and some pride in one of them… :) ).

    As for nurturing budding hackers — re-use is a cornerstone of good development practice, and constructive laziness (the ability to do a cost-benefit analysis on work, over the long-run) is a hallmark of a great developer. Learning how to find what you need helps prevent wasted effort, and allows everyone to work together to make something that’s better than what we could make by ourselves. It’s a skill that, in my opinion, is just as essential as being able to learn how a system works. Furthermore, being able to read and understand other people’s codebase is an absolutely critical skill that you cannot gain by writing everything yourself.

    Getting in the habit of self-supplying can also lead to Not Invented Here Syndrome (not that you suffer from it, but I’ve dealt with several groups that have). In these cases, doing it “in-house” starts to become more valuable than actually finishing the product — usually with chants of “we understand the codebase better” and “we have more control this way.” It’s easy to waste vast amounts of time and energy in writing systems from scratch, at best canceling out any benefits gained from internal production. In the professional world, it hurts the bottom line; in the personal world, it’s self-indulgent at best (not necessarily a bad thing), and an unfortunate waste of time at worst.

  4. I think my last line didn’t sound exactly right because you bring up a good point. “Re-use is a cornerstone of good development.” I totally agree. I pretty much agree with everything you said.

    All I’m saying is that this is a tutorial series on learning to use custom fields. This is code that others can use or “re-use” to develop bigger and better things. Mostly, it’s an experiment for me. I’m learning to use custom fields in different ways as I go.

    Sure, there may be better and easier ways to do things, and I’m glad you pointed out your plugin. I haven’t tested it, but I’ve read the page you linked to and it looks great. People should definitely use it for things like this, if that’s what they want.

    I think I may have sounded like I’m becoming an “in-house” type of developer with my last comment, but this is far from the truth. If this was the case, I’d still be working on making my own blogging system. I just want to continue learning and then provide what I’ve learned back to the community. It’s up to the community to decide whether they want to use it.

    One point I do disagree on is that it’s “an unfortunate waste of time.” I don’t think it’s a waste of time because this is what I enjoy doing and how I enjoy doing it. Especially since this blog is not part of the “professional world.” It’s a personal blog where I don’t have a deadline to meet or a job that just has to get done. It’s my Web experience.

    As far as popping up in the search rankings, there’s not much I can do about that, except for make my site worse. :) I’m really hoping to go up in the search rankings for custom field tutorials though.

  5. *lol*

    No, no, you need to blast your page right now! ;)
    We are, it appears, in violent agreement. I really do appreciate you putting the effort into documenting the process as you go; I’ve meant to do the same thing many times over, but I’m better at mentoring one-on-one than conveying information in more general write-ups. I’d be happy to share my techniques and experiences with you, if you think they’d be helpful; I’d love to see that information passed on in a more accessible manner.

  6. Hello,

    I just wanted to thank you for putting up this tutorial.

    I recently was having problems with In Series (it seems to be clashing with one of my other plugins or something else on my site) and I was looking to find another solution (Plus, the recent in-series upgrades have now eliminated the possiblity of displaying the series in a sidebar, and since I can’t downgrade…). It’s still a great plugin, it just doesn’t seem right for my site at the moment.

    Searching for a new solution, I first stumbled across Organize Series…only to discover that it doesn’t work with WP 2.3.

    Thinking I was out of luck, I stumbled across your site…and it was exactly what I was looking for.

  7. Reid
    Well, thanks for using it. It’s not the most elegant solution as far as listing articles in a series, but it definitely works.

  8. This is great stuff. I’m trying to do something similar, but listing related posts for a single post based on the tags of the main post. I’ve explained it a hair better here:

    http://wordpress.org/support/topic/162462?replies=1

    You obviously have a deeper PHP understanding than I do and I’ve tried to modify your code to fit for 2 days (I wish I was exaggerating). Do you have any ideas how I can create a secondary loop, on single.php, that’ll list any posts using the same tag(s) the main post does without including the main post itself. It seems easy conceptually but damned if I know…

  9. you save my life…..thank you

  10. Great tutorial - thanks.
    I have one question though. How do add a check to ensure that other posts in the series are actually published?
    For example, I may write a series that is published over several days. When I write the post I will add the key and let WP take care of the scheduling. BUT when the first of the series is published it shows the h3 and an empty list until the next one is published.

    How can I avoid that?

Leave a reply

Log in or Register



XHTML: You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> 
<blockquote cite=""> <cite> <code> <del datetime=""> <em> 
<q cite=""> <strong>