WordPress provides a function called post_class()
that outputs various class names for the post being referenced. This is most often used on post listing template files, such as index.php
& archive.php
, as well as the single.php
template file.
You’ll often see it in your theme like this:
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
The default classes that WordPress adds DO NOT include classes for odd & even posts. If you want to style your odd/even posts differently, we’ll extend the post_class()
function to include an extra class for “odd” or “even.”
Add “Odd” & “Even” Post Classes
There are two ways to include this code: create a plugin, or add directly to your functions.php
file.
// Adds 'odd' and 'even' classes to each post function wpsd_oddeven_post_class ( $classes ) { global $current_class; $classes[] = $current_class; $current_class = ($current_class == 'odd') ? 'even' : 'odd'; return $classes; } add_filter ('post_class', 'wpsd_oddeven_post_class'); global $current_class; $current_class = 'odd';
If you view the source code of a post listing page, you should see either “odd” or “even” applied to each post listing. The first one will always start with “odd.”
“Odd” Class Added to Single Posts
The above code will add an “odd” class to all single posts (single.php
). This isn’t very useful for styling purposes, and I can’t think of a reason why you’d need it.
If anyone can provide an update to this code that only applies odd/even classes to non-single references to post_class()
, we’d appreciate it. I tried various options using the ! is_single()
conditional statement, but couldn’t find a solution.
Reference post_class() in the WordPress Codex.
Martin Scott / #
Maybe wrap the whole function in a conditional to only apply to the home page:
global $current_class;
if(is_home() && !is_paged()):
// rest of code
endif;
return $classes;
Webdigital / #
Hello Dave, i was thinking is this can be done with a 3rd elemen?
At this moment i’m in the need of:
– odd
– even
– even
Dave Warfel (Author) / #
I’m not sure how to add a class name to every third element, but if you just need styling, you could try using CSS instead.
Use the
:nth-child
selectors.This would select every third
<p>
tag inside of a<div>
.Learn more: https://css-tricks.com/useful-nth-child-recipies/