将类添加到wordpress循环

时间:2014-05-17 23:21:08

标签: wordpress post

我会在前四个帖子中添加课程。 要在html上打印如下:

 <post id="post-1"  class="classes first">
 <post id="post-2" class="classes second">
 <post id="post-3" class="classes third">
 <post id="post-4" class="classes fourth">

My Loop:

<?php query_posts('cat=15'); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
</div>
<?php endwhile; endif; ?>

非常感谢

2 个答案:

答案 0 :(得分:3)

你可以这样做:

<?php query_posts('cat=15'); ?>
<?php $count = 1; ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" class="post<?php echo $count; ?>">
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<?php the_content(); ?>
</div>
<?php $count++; ?>
<?php endwhile; endif; ?>

在css中,使用div.post1,div.post2,div.post3和div.post4

答案 1 :(得分:1)

如果您使用的是post_class函数

,则可以使用post_class过滤器
add_filter( 'post_class', 'add_class_to_first_four' );

function add_class_to_first_four( $classes ) {

    global $wp_query;

    $cur = $wp_query->current_post;

    if ( 0 == $cur ) $classes[] = 'first';

    if ( 1 == $cur ) $classes[] = 'second';

    if ( 2 == $cur ) $classes[] = 'third';

    if ( 3 == $cur ) $classes[] = 'fourth';

    return $classes;
}