Last active
February 1, 2016 17:29
-
-
Save mboynes/5657510 to your computer and use it in GitHub Desktop.
wp_cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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