WordPress posts are usually displayed as full posts. Now let's say that we want to display them in a compact way, e.g. the first post in full followed by an unordered list of posts which also feature a post thumbnail. Let's see the details.
We can add the following code to the functions.php
file:
function compact_posts() { $first_loop = new WP_Query(array('posts_per_page' => 1)); $id = null; if($first_loop->have_posts()) { while ($first_loop->have_posts()) : $first_loop->the_post(); $id = get_the_ID(); ?> <div class="post-single"> <h2><a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a></h2> <?php if ( has_post_thumbnail() ) {?> <?php if(is_home()) {?> <div class="featured-thumbnail"> <?php the_post_thumbnail(array(220,180));?> </div> <?php }?> <?php } ?> <div class="post-meta"> <span class="date"><?php the_time('F j, Y');?></span> <span class="author"><?php _e(', by '); the_author_posts_link(); ?></span> <span class="comments"><?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?></span> <span class="category"><?php _e('Categories: '); the_category(', ') ?></span> <span class="tags"><?php if (the_tags('Tags: ', ', ', ' ')); ?></span> </div> <div class="post-content"> <?php the_content(__('Read more'));?> </div> </div> <?php endwhile; wp_reset_query(); } $second_loop = new WP_Query(array('posts_per_page' => 4, 'post__not_in' => array($id))); if($second_loop->have_posts()) {?> <div id="other-posts"> <h2>Other posts</h2> <ul><?php while ($second_loop->have_posts()) : $second_loop->the_post();?> <li><?php the_post_thumbnail(array(70,70));?><a href="<?php the_permalink();?>" rel="bookmark"><?php the_title();?></a></li> <?php endwhile; wp_reset_query(); echo '</ul></div>' . "\n"; } }
We've used two Loops here: the last Loop excludes the first post (previously fetched) by using its ID stored in the $id
variable. Then we can add our function to the main index.php
file:
<?php if(is_home()) { compact_posts(); } ?>
You can see the result below.
I can't believe I just found this out, I had a friend hack me something like this with 2 times the code : (.
It's time I picked up some books again.