我为这样的事情编写了一个助手函数。这是我所有主题功能的第一件事。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
* cycle classes.
* For instance, foreach ($posts as $post) { echo \'<div class="\'.wp_cycle(\'odd\',\'even\').\'">...</div>\'; }
* would alternate between <div class="odd">...</div> and <div class="even">...</div>. Neat, huh?
* 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
* @author Matthew Boynes
*/
function wp_cycle() {
global $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 ] ];
}
一旦将其添加到函数中。php文件,在循环中使用它非常简单。下面是一个示例:
<?php while ( have_posts() ) : the_post(); ?>
<div class="<?php post_class( wp_cycle( \'\', \'\', \'custom-class\', \'custom-class\' ) ) ?>">
<!-- ... -->
</div>
<?php endwhile; ?>
有一个警告:如果WordPress在core中添加了类似的内容,我总是用一些不太通用、更特定于站点的内容来替换wp\\u0。例如,如果我为美国有线电视新闻网(CNN)制作一个网站,它将是CNN\\U cycle。