The post_class filter allows you to modify the list of CSS class names for the current WordPress post.
Usage
function my_add_custom_class($classes, $class, $post_id) { // your custom code here return $classes; } add_filter('post_class', 'my_add_custom_class', 10, 3);
Parameters
$classes string[]
: An array of post class names.$class string[]
: An array of additional class names added to the post.$post_id int
: The post ID.
Examples
Adding a custom class to all posts
function add_custom_class($classes, $class, $post_id) { $classes[] = 'custom-class'; return $classes; } add_filter('post_class', 'add_custom_class', 10, 3);
This code snippet adds a ‘custom-class’ CSS class to all posts on your WordPress site.
Add a class based on post format
function add_post_format_class($classes, $class, $post_id) { $format = get_post_format($post_id); $classes[] = 'format-' . $format; return $classes; } add_filter('post_class', 'add_post_format_class', 10, 3);
This example adds a CSS class based on the post format (e.g., ‘format-video’, ‘format-gallery’).
Adding a class based on post category
function add_category_class($classes, $class, $post_id) { $categories = get_the_category($post_id); if (!empty($categories)) { $classes[] = 'category-' . $categories[0]->slug; } return $classes; } add_filter('post_class', 'add_category_class', 10, 3);
This code snippet adds a CSS class based on the first post category (e.g., ‘category-news’, ‘category-tutorials’).
Adding a class for featured posts
function add_featured_post_class($classes, $class, $post_id) { if (get_post_meta($post_id, 'featured_post', true)) { $classes[] = 'featured-post'; } return $classes; } add_filter('post_class', 'add_featured_post_class', 10, 3);
This example adds a ‘featured-post’ CSS class to posts marked as featured using a custom post meta field.
Add an ‘even’ or ‘odd’ class to posts
function add_even_odd_post_class($classes, $class, $post_id) { global $wp_query; $classes[] = ($wp_query->current_post % 2 == 0) ? 'even' : 'odd'; return $classes; } add_filter('post_class', 'add_even_odd_post_class', 10, 3);
This code snippet adds an ‘even’ or ‘odd’ CSS class to posts, allowing for easy styling of alternate post layouts.