【发布时间】:2026-01-13 07:00:01
【问题描述】:
我有一系列自定义帖子类型的帖子。它们每个都有一张特色图片(缩略图)和一段摘录。
我想在主页上显示 4 个项目,其中第一个项目的格式与其他 3 个不同,例如在附件中。这是怎么做到的?
【问题讨论】:
标签: wordpress-theming wordpress
我有一系列自定义帖子类型的帖子。它们每个都有一张特色图片(缩略图)和一段摘录。
我想在主页上显示 4 个项目,其中第一个项目的格式与其他 3 个不同,例如在附件中。这是怎么做到的?
【问题讨论】:
标签: wordpress-theming wordpress
您可以为此使用计数器。请参阅下面的示例
<?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();
?>
【讨论】:
$the_query->current_post查看帖子索引。这样,就不需要创建计数器了。
全局 $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 中的第一个项目的样式。
【讨论】: