最近5个帖子(自定义帖子类型),每个帖子都有不同的css

时间:2012-11-13 作者:rwzdoorn

在创建我们的投资组合时,我想用一行最新的5/6特色图片制作一个动态标题。所有这些帖子都来自“应用程序”自定义帖子类型。

<div id="header">
        <div class="latest_post"> <img src="featured image" class="class-name" /></div>
        <div class="second_post"> <img src="featured image" class="class-name" /> </div>
        <div class="third_post"> <img src="featured image" class="class-name" /> </div>
        <div class="fourth_post"> <img src="featured image" class="class-name" /> </div>
        <div class="fifth_post"> <img src="featured image" class="class-name" /> </div>
 </div>
我如何创建这样的东西?

提前谢谢。

2 个回复
最合适的回答,由SO网友:jzatt 整理而成

首先设置WP\\u查询,从自定义帖子类型“apps”中获取最新的5篇帖子。您还需要为循环中的每个帖子更新一个“计数器”。然后简单地在类中回显div的计数。

<?php
//Query posts
$query = new WP_Query(array(
    \'post_type\' => \'apps\',
    \'posts_per_page\' => 5
));
//Reset counter
$count = 0;
?>

<?php if ($query->have_posts()) : ?>

<div id="header">
    <?php while ($query->have_posts()) : $query->the_post(); ?>
    <?php $count++; //update count ?>
        <div class="post_<?php echo $count; //prints the class as "post_XX" ?>">
            <?php if( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
        </div>
    <?php endwhile; ?>
</div>

<?php endif; ?>
<?php wp_reset_query(); ?>
这将返回以下结果

<div class="post_1"><img src=".." /></div>
<div class="post_2"><img src=".." /></div>
<div class="post_3"><img src=".." /></div>
<div class="post_4"><img src=".." /></div>
<div class="post_5"><img src=".." /></div>

SO网友:Michael

一个二次回路WP_Query(); 使用循环计数器$query->current_post 从一个数组中输出这五个css类;

示例(基于jzatt的代码):

<?php
$query = new WP_Query(array(
    \'post_type\' => \'apps\',
    \'posts_per_page\' => 5,
    \'meta_key\' => \'_thumbnail_id\'
));
$css_classes = array( \'latest\', \'second\', \'third\', \'fourth\', \'fifth\' ); ?>

<?php if ($query->have_posts()) : ?>

<div id="header">
    <?php while ($query->have_posts()) : $query->the_post(); ?>
        <div class="<?php echo $css_classes[$query->current_post%5]; ?>_post"> <?php the_post_thumbnail(\'thumbnail\',array(\'class\' => \'class-name\' )); ?> </div>
    <?php endwhile; ?>
</div>

<?php endif; wp_reset_postdata(); ?>
调整\'thumbnail\' 您的特色图像大小;对于6个职位,更改为posts_per_page\' => 6,, 再添加一个\'sixth\' 元素,并更改$query->current_post%5$query->current_post%6

结束

相关推荐

get_posts by id not working

我有以下代码:global $post; $current_post = $post->ID; $array=range(1,$current_post); $posts = get_posts(\'numberposts=5&post__in=\' . $array . \'&category=\'. $category->term_id . \'&exclude=\' . $current_post); 出现的错误为Warning: