以不同的方式设置WP_Query中的第一篇文章

时间:2012-11-22 11:47:35

标签: php wordpress

我有一个WP_Query循环,它提取了最近的4篇文章:

    <?php
    $featuredPosts = new WP_Query();
    $featuredPosts->query('showposts=4');
    while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>
    <div class="recentpost">

    <?php echo get_the_post_thumbnail ($_post->ID, 'small'); ?>

    <div class="titlerecent">
    <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
    </div>

    </div>
    <?php endwhile; ?>

我想要做的是修改它并将循环中的第一个帖子设置为不同的样式。我不只是想为它添加一个CSS类,我想用完全不同的<div>包装它。

所以我希望将第一篇文章包含在<div class="homefirstpost">中,然后将剩余的3篇文章包含在<div class="recentpost">内。

我需要做什么?

2 个答案:

答案 0 :(得分:1)

我会这样做:

<?php
$isfirst = false;

$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=4');
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>

    <?php if ( ! $isfirst ): ?>
    <div class="homefirstpost">
        <?php $isfirst = true; ?>
    <?php else: ?>
    <div class="recentpost">
    <?php endif; ?>

    <?php echo get_the_post_thumbnail ($_post->ID, 'small'); ?>

    <div class="titlerecent">
    <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
</div>
<?php endwhile; ?>

答案 1 :(得分:0)

当您的帖子包装在另一个容器中时,您可以使用:first-child选择器作为第一篇文章。有关详细信息,请参阅Selectors

当你的HTML看起来像这样:

<div id="featuredPosts">
    <div>First Post ...</div>
    <div>Next Post ...</div>
    <div>Next Post ...</div>
    <div>Next Post ...</div>
</div>

你可以沿着这些方向使用CSS:

div#featuredPosts > div:first-child {
some special styles;
}