[英]Style the first post in WP_Query differently
我有一個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">
。
我需要做什么?
我會這樣做:
<?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; ?>
當您的帖子包裝在另一個容器中時,可以對第一篇帖子使用:first-child
選擇器。 有關詳細信息,請參見選擇器 。
當您的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.