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.
We Recommend
https://kinsta.com › wordpress-hosting
Fast and secure infrastructure, worldwide CDN, edge caching, 35 data centers, and enterprise-level features included in all plans. Free site migrations.
https://gravityforms.com › features
Create custom web forms to capture leads, collect payments, automate your workflows, and build your business online. All without ever leaving WordPress.
Leave a Comment