Skip to content

Instantly share code, notes, and snippets.

@mboynes
Last active February 1, 2016 17:29
Show Gist options
  • Save mboynes/5657510 to your computer and use it in GitHub Desktop.
Save mboynes/5657510 to your computer and use it in GitHub Desktop.
wp_cycle
<?php
/**
* Cycle/alternate unlimited values of a given array.
*
* For instance, if you call this function five times with
* `wp_cycle( 'three', 'two', 'one' )`, you will in return get: three two one
* three two. This is useful for loops and allows you to do things like cycle
* HTML classes.
*
* EXAMPLE
*
* foreach ( $posts as $post ) {
* echo '<div class="'.wp_cycle('odd','even').'">...</div>';
* }
*
* This would alternate between `<div class="odd">...</div>` and
* `<div class="even">...</div>`.
*
* You can pass any data as args and as many as you want, e.g.
* `wp_cycle( array( 'foo', 'bar' ), false, 5, 'silly' )`
*
* @param mixed Accepts unlimited args
* @return mixed
*/
function wp_cycle() {
static $wp_cycle_curr_index;
$args = func_get_args();
$fingerprint = substr( sha1( serialize( $args ) ), 0, 7 );
if ( ! is_array( $wp_cycle_curr_index ) ) {
$wp_cycle_curr_index = array();
}
if ( ! isset( $wp_cycle_curr_index[ $fingerprint ] ) || ! is_int( $wp_cycle_curr_index[ $fingerprint ] ) ) {
$wp_cycle_curr_index[ $fingerprint ] = -1;
}
$wp_cycle_curr_index[ $fingerprint ] = ++$wp_cycle_curr_index[ $fingerprint ] % count( $args );
return $args[ $wp_cycle_curr_index[ $fingerprint ] ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment