0

我有一系列自定义帖子类型的帖子。他们每个人都有一张特色图片(缩略图)和一段摘录。

我想在主页上显示 4 个项目,第一个项目的格式与其他 3 个不同,例如在附加的图像中。这是怎么做的?

在此处输入图像描述

4

2 回答 2

7

您可以为此使用计数器。请参阅下面的示例

 <?php
  $inc = 1;
  $the_query = new WP_Query();
  $the_query->query("posts_per_page=4");
  if ($the_query->have_posts()) : 
  while($the_query->have_posts()) : $the_query->the_post();
  if($inc == 1){ 
   //first post here
   //do stuffs here
  }
 else{
  //the rest of the posts
 }

 $inc++; //counter
 endwhile; 
 endif; 
 wp_reset_postdata();
 ?>
于 2012-12-02T03:08:15.400 回答
0

全局$wp_query包含有关当前查询的所有内容,包括参数、结果、结果内容和查询本身。

您要检查$wp_query->current_post,如果它是 0,那么它是循环的第一个帖子。

if ( $wp_query->current_post === 0 ) {
    // first post
} else {
    // the rest
}

但是,如果您有很多帖子和分页,那么每个页面的第一个帖子的索引为 0。

如果您只想定位第一页的第一篇文章,那么:

if ( $wp_query->current_post === 0 && $wp_query->query_vars['paged'] === 0 ) {
    // first post in first page only
} else {
    // the rest
}

单线将是:

$class = ( $wp_query->current_post === 0 ) ? ' first_item' : '';

然后添加$class到您的项目包装器中,以便您可以为 CSS 中的第一个项目设置样式。

于 2021-08-31T11:34:36.633 回答