我正在为我的乐队制作一个WordPress网站,我想在我们的博客页面上标记每三篇文章,以便为其应用一个特殊的类,有人对如何实现这一点有什么建议吗?非常感谢您的帮助,谢谢!摇滚乐。
How to mark every 3rd post
5 个回复
最合适的回答,由SO网友:fuxia 整理而成
我的方法。无额外功能,无过滤器。:)
<?php $GLOBALS[\'wpdb\']->current_post = 0; ?>
<div <?php post_class( 0 === ++$GLOBALS[\'wpdb\']->current_post % 3 ? \'third\' : \'\' ); ?>>
备选方案:<div <?php post_class( 0 === ++$GLOBALS[\'wpdb\']->wpse_post_counter % 3 ? \'third\' : \'\' ); ?>>
SO网友:kaiser
作为对helgathevikings答案的补充
使用post\\u class()fn而不污染全局命名空间static
类中的变量允许与全局变量相同的行为:它们保持不变,不会更改,除非您不更改它们function wpse44845_add_special_post_class( $classes )
{
// Thanks to @Milo and @TomAuger for the heads-up in the comments
0 === $GLOBALS[\'wpdb\']->current_post %3 AND $classes[] = \'YOUR CLASS\';
return $classes;
}
add_filter( \'post_class\',\'wpse44845_add_special_post_class\' );
更新我们可以利用current_post
全球的财产$wp_query
对象让我们使用匿名函数use
关键字,传递全局$wp_query
参考(PHP 5.3+):
add_filter( \'post_class\', function( $classes ) use ( &$wp_query )
{
0 === $wp_query->current_post %3 AND $classes[] = \'YOUR CLASS\';
return $classes;
} );
进一步,我们可以将其限制在主回路中,并使用in_the_loop()
条件检查。SO网友:helgatheviking
如果您的主题使用post\\u class()生成post类,您可以尝试。我不能百分之百确定它将如何处理分页b/c我在本地安装上没有足够的帖子来测试它
add_filter(\'post_class\',\'wpa_44845\');
global $current_count;
$current_count = 1;
function wpa_44845( $classes ){
global $current_count;
if ($current_count %3 == 0 ) $classes[] = \'special-class\';
$current_count++;
return $classes;
}
SO网友:kaiser
$i = 0;
if ( have_posts ) :
while( have_posts ) :
the_post();
$class = \'class="BASIC-CLASS\';
if ( 0 === ( $i % 3 ) )
$class .= \'YOUR-SPECIAL-CLASS\';
$class .= \'"\';
echo "<div {$class}>";
// do stuff
echo \'</div>\';
$i++;
endwhile;
endif;
SO网友:rohmann
使用CSS和javascript也可以做到这一点。
使用CSS3,您可以使用第n个子选择器将每三篇文章作为目标。
article.post:nth-child(3n+0)
{
background-color: #777;
}
或者使用jQuery,您可以使用相同的技术添加CSS类。jQuery(function($) {
$( "article.post:nth-child(3n+0)" ).addClass("custom-class");
});
结束