Come creare uno shortcode per mostrare gli ultimi 2 articoli
Vorrei creare uno shortcode che mostri gli ultimi 3 articoli in qualsiasi pagina...
Dovrebbe essere formattato così:
Titolo
Estratto...Leggi tutto
Ho aggiunto questo codice nel file functions.php
function my_recent_post()
{
global $post;
$html = "";
$my_query = new WP_Query( array(
'post_type' => 'post', // Tipo di contenuto: articoli
'posts_per_page' => 2 // Numero di articoli da mostrare
));
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
$html .= "<h2>" . get_the_title() . " </h2>";
$html .= "<p>" . get_the_excerpt() . "</p>";
$html .= "<a href=\"" . get_permalink() . "\" class=\"button\">Leggi tutto</a>";
endwhile; endif;
return $html;
}
add_shortcode( 'recent', 'my_recent_post' ); // Registra lo shortcode [recent]
e funziona, tranne per il fatto che ora la mia homepage mostra i 2 articoli come desiderato in una sezione, ma il problema è che sotto il contenuto, cioè sotto la sezione con lo shortcode, mostra l'intero secondo articolo (vedi immagine).
Qualche suggerimento?
Aggiungi wp_reset_postdata()
dopo il tuo ciclo while
:
endwhile;
wp_reset_postdata();
endif;
Questo assicurerà che, dopo l'esecuzione del tuo shortcode, venga ripristinato il post effettivamente corrente, in modo che i tag del template visualizzino i dati corretti.

inserisci il codice qui
testo in grassetto puoi provare questo
function my_recent_post()
{
global $post;
$html = "";
$my_query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 2
));
if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post();
$html.= get_template_part( 'content', 'excerpt' );
endwhile; endif;
return $html;
}
add_shortcode( 'recent', 'my_recent_post' ); ?>
**<h1>crea un file php content-excerpt.php e inseriscilo nel tuo tema</h1>
codice di quel file è**
<article id="post-<?php the_ID(); ?>">
<header class="entry-header">
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
</div>
</header>
<div class="entry-excerpt">
<?php the_excerpt(); ?>
</div>
<a href="<?php get_permalink() ?>" class="button">Leggi tutto</a>
</article>

Come funzionerà? get_template_part
stamperà il contenuto, non lo restituirà.
