WP-Mix

A fresh mix of code snippets and tutorials

WordPress Random Post Class

Here is a simple plugin that you can use to include a random post class for each post. With a slight modification it can be used to include a random body class. This function can be useful for applying random colors and styles to your blog posts. Or whatever.

<?php
/*
	Plugin Name: Random Post Class
	Plugin URI: https://plugin-planet.com/
	Description: Adds a random class to all posts.
	Author: Jeff Starr
	Author URI: https://monzillamedia.com/
	Donate link: https://m0n.co/donate
	Version: 1.0
	License: GPL v3
*/

function shapeSpace_random_post_class($classes) {
	
	$random = rand(1, 9);
	
	$classes[] = 'random-'. $random;
	
	return $classes;
	
}
add_filter('post_class', 'shapeSpace_random_post_class');

To apply the random class to the <body> tag, replace the last line with this:

add_filter('body_class', 'shapeSpace_random_post_class');

To use this code as a plugin, create a new PHP file in your /plugins/ directory. Or to add via your theme template, simply add the function and filter (you don’t need to include the file header comment infos) to your theme’s functions.php file.

The result of this function is a class named random-x, where x is a number from 1 to 9. Learn more about PHP’s rand() function.

Learn more

WordPress Themes In Depth