是否可以在查询中以2为增量向帖子/页面添加特定类?
例如
第1篇第2篇第3篇(添加自定义类)第4篇(添加自定义类)第5篇第6篇第7篇(添加自定义类)第8篇(添加自定义类)第9篇如果需要,我不介意使用jQuery。
是否可以在查询中以2为增量向帖子/页面添加特定类?
例如
第1篇第2篇第3篇(添加自定义类)第4篇(添加自定义类)第5篇第6篇第7篇(添加自定义类)第8篇(添加自定义类)第9篇如果需要,我不介意使用jQuery。
滤器post_class
, 在筛选器回调中使用静态内部计数器:
add_filter( \'post_class\', \'wpse_100804_post_class\' );
function wpse_100804_post_class( $classes )
{
static $counter = 0;
$counter += 1;
switch ( $counter )
{
case 4:
$counter = 0;
case 3:
$classes[] = \'extra\';
}
return $classes;
}
在循环模板调用中post_class()
像这样:while ( have_posts() )
{
the_post();
?><li <?php post_class(); ?>>
<?php /* more stuff */ ?>
</li>
}
如果这是一个你可以安全编辑的主题(即你已经构建的主题),那么在你的循环中,以4为周期跟踪帖子。
$qry = new WP_Query("showposts=10");
if ($qry->have_posts()) {
$iter = 0;
while($qry->have_posts()) {
$iter++;
$extra_class = \'\';
$qry->the_post();
if (3 == $iter || 4 == $iter) {
$extra_class = \'extra-class\';
}
echo \'<div \',post_class($extra_class),\'>\';
the_title();
echo \'</div>\';
if (4 == $iter) {
$iter = 0;
}
}
}
这是一个较短的版本,使用modulus 4
在$wp_query->current_post
while ( have_posts() ) : the_post(); ?>
<li <?php echo ( $wp_query->current_post % 4 > 1 ) ? " class=\'custom-class\' " : ""; ?>>
<?php the_title();?>
</li>
endwhile;
这是一张表格,显示了当$wp_query->current_post % 4 > 1
我为这样的事情编写了一个助手函数。这是我所有主题功能的第一件事。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。我正在试图找到一种方法来禁用IE8或更少版本中的任何东西的212样式表。是否有一个条件代码可以放在我的函数php文件中,使默认的Twentylex样式表(及其子主题子表)在这些特定浏览器中被忽略?我想从一块空白的石板上开始我的IE only样式表,并且只应用非常非常简单的样式。提前感谢