Skip to content

Instantly share code, notes, and snippets.

@jbutko
Forked from rodgerthat/do_color_classes.php
Created May 27, 2013 18:40
Show Gist options
  • Save jbutko/5658477 to your computer and use it in GitHub Desktop.
Save jbutko/5658477 to your computer and use it in GitHub Desktop.
WP, PHP: Add classes for every (nth) element
/************* ADDING CLASSES TO POST_CLASS **************/
// every post has a few uniquely colored elements, rather than rely on CSS nth-magic, and to keep things smooth
// and not conflict w/ trying to use jQuery nth-magic in tandem w/ the endless scroll,
// the option is to get the server to do the heavy lifting,
// ideally it would be nice to pass the array of classes to iterate thru into the filter,
/**
*
* @param $classes
* @return array
*/
function do_color_classes( $classes ) {
// globalizations
global $wp_query;
global $array_index;
// define an array of class names to iterate over
$classes_array= array( 'yellow', 'red', 'blue' );
// get the post count
$count = $wp_query->current_post;
// set the array index value
if ( $count == 0 )
$array_index = 0;
// compensate for it starting @ 0;
$count = $count++;
// pass the class in to match the index.
$classes[] = $classes_array[$array_index];
// check the modulus, divide the post count by the length of the array,
// this'll reset the index counter, and keep iterating thru the $color_classes
if ( $count % sizeof($classes_array) == 0 )
// reset the index
$array_index = 0;
else
// +1 to the index
$array_index++;
return $classes;
}
add_filter( 'post_class', 'do_color_classes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment