我编写了一个函数来帮助实现这一点,以便在功能上模仿Ruby on Rails的cycle
助手:
/**
* Cycle/alternate unlimited values of a given array.
*
* For instance, if you call this function five times with
* `cycle_it( \'three\', \'two\', \'one\' )`, you will in return get:
* three two one three two
*
* This is useful for loops and allows you to cycle classes.
*
* Example:
*
* foreach ( $posts as $post ) {
* printf(
* \'<div class="%s">...</div>\',
* esc_attr( cycle_it( \'odd\', \'even\' ) )
* );
* }
*
* 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.
*
* cycle_it( array( \'foo\', \'bar\' ), false, 5, \'silly\' )
*
* @param mixed ...$args Any number of arguments to cycle.
* @return mixed Alternating value passed through the function arguments.
*/
function cycle_it() {
static $cycle_curr_index;
$args = func_get_args();
$fingerprint = sha1( serialize( $args ) );
if ( ! is_array( $cycle_curr_index ) ) {
$cycle_curr_index = array();
}
if ( ! is_int( $cycle_curr_index[ $fingerprint ] ) ) {
$cycle_curr_index[ $fingerprint ] = -1;
}
$cycle_curr_index[ $fingerprint ] = ++$cycle_curr_index[ $fingerprint ] % count( $args );
return $args[ $cycle_curr_index[ $fingerprint ] ];
}
如果您将其添加到主题的功能中。php文件,然后可以将代码更改为:
回响<div id="seasonBlock" class="span-12\' . esc_attr( cycle_it( \'\',\' last\' ) ) . \'" >\';