Immaginiamo di voler visualizzare i nostri post nella home page in modo compatto, ossia il primo post in modo normale e gli altri post come un elenco di link contenenti ciascuno la thumbnail del post. Vediamo come fare.
Aggiungiamo il seguente codice al file functions.php
:
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();?>"><?php the_title();?></a></li>
<?php
endwhile;
wp_reset_query();
echo '</ul></div>' . "\n";
}
}
Abbiamo usato due Loop: nel primo abbiamo visualizzato l'ultimo post per intero e nel contempo abbiamo memorizzato il suo ID nella variabile $id
, mentre nel secondo abbiamo visualizzato come elenco altri quattro post escludendo il post precedentemente visualizzato (tramite il suo ID).
Quindi aggiungiamo la funzione al file index.php
:
<?php
if(is_home()) {
compact_posts();
}
?>
Potete visualizzare il risultato di seguito.