Latest 5 posts (custom post type), each post different CSS

While creating our portfolio i’d like to make a dynamic header with the latest 5/6 featured images in a row. All these posts come out of the ‘apps’ custom post type.

<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>

How would I create something like this?

Read More

Thanks in advance.

Related posts

Leave a Reply

2 comments

  1. First setup a WP_Query to fetch the latest 5 posts from your custom post type “apps”. You also need to update a “counter” for each post in the loop. Then simply echo the count in the class for the 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(); ?>
    

    This should return the results as

    <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>
    
  2. one secondary loop with WP_Query(); use the loop counter $query->current_post to output those five css classes from an array;

    example (based on the code by 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(); ?>
    

    adjust 'thumbnail' to your featured image size;
    for 6 posts, change to posts_per_page' => 6,, add a further 'sixth' element to the array of css classes, and change $query->current_post%5 to $query->current_post%6