Ottenere i post recenti con anteprima
Voglio ottenere diversi post recenti. Quindi uso wp_get_recent_posts. Ma ottengo solo la prima immagine.
<?php $args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </li> ';
if ( has_post_thumbnail() ) {
the_post_thumbnail('thumbnail');
}
}
?>

In realtà, la condizione restituisce sempre false perché non stai passando l'ID del post alla funzione has_post_thumbnail()
e la funzione ottiene sempre il valore predefinito che è null
.
has_post_thumbnail( $recent["ID"] )
.
Lo stesso vale per la funzione get_the_post_thumbnail()
.
get_the_post_thumbnail( $recent["ID"] )
.
$args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts($args);
foreach( $recent_posts as $recent ){
if ( has_post_thumbnail( $recent["ID"]) ) {
echo get_the_post_thumbnail($recent["ID"],'thumbnail');
}
}
Ma se usi le funzioni has_post_thumbnail();
e get_the_post_thumbnail()
all'interno del The_Loop
di WordPress, allora non è necessario passare l'ID del post.
$args = array( 'posts_per_page' => '3' );
$recent_posts = new WP_Query($args);
while( $recent_posts->have_posts() ) {
$recent_posts->the_post() ;
if ( has_post_thumbnail() ) {
echo get_the_post_thumbnail();
}
}
wp_reset_postdata();

Per utilizzare the_post_thumbnail
, è necessario inizializzare un loop. Quindi sarebbe meglio così:
<?php
$args = array( 'posts_per_page' => '3' );
$recent_posts = new WP_Query($args);
while( $recent_posts->have_posts() ) :
$recent_posts->the_post() ?>
<li>
<a href="<?php echo get_permalink() ?>"><?php the_title() ?></a>
<?php if ( has_post_thumbnail() ) : ?>
<?php the_post_thumbnail('thumbnail') ?>
<?php endif ?>
</li>
<?php endwhile; ?>
<?php wp_reset_postdata(); # resetta i dati del post così che altre query/loop funzionino ?>
(Ho inserito l'anteprima all'interno dei tag <li>
perché qualsiasi cosa oltre a <li>
all'interno di <ol>
o <ul>
è HTML non valido.)
