Skip to content

Instantly share code, notes, and snippets.

@vc27
Forked from rodgerthat/do_color_classes.php
Created May 3, 2012 22:15
Show Gist options
  • Save vc27/2589904 to your computer and use it in GitHub Desktop.
Save vc27/2589904 to your computer and use it in GitHub Desktop.
Considerations: Iterating through an array of class names and adding them to the Post Class
<?php
/************* 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' );
/**
* Note:
* consider a filter on your array that will allow you to do more
* outside of this function. Although at some point you may as well
* just run the code here.
**/
$classes_array = apply_filters( 'filter_color_classes', 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 + 1;
// 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;
}
/**
* Note:
* post_class filter found - wp-includes/post-template.php line 296
* This filter only has 2 possible parameters and neither are usable to
* pass extra data.
*
* function post_class( $class = '', $post_id = null ) { ... }
**/
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