Cómo crear un shortcode para mostrar los 2 últimos posts en WordPress
Me gustaría crear un shortcode que muestre los últimos 3 posts en cualquier página...
Debería mostrarse de esta forma:
Título
Extracto... Leer más
He añadido este código en functions.php
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 .= "<h2>" . get_the_title() . " </h2>";
$html .= "<p>" . get_the_excerpt() . "</p>";
$html .= "<a href=\"" . get_permalink() . "\" class=\"button\">Leer más</a>";
endwhile; endif;
return $html;
}
add_shortcode( 'recent', 'my_recent_post' );
y funciona, excepto que ahora mi página principal muestra los 2 posts como se desea en una división, pero el problema es que debajo del contenido, es decir, debajo de la división con el shortcode, muestra el artículo completo del segundo post (ver imagen).
¿Alguna sugerencia?

Añade wp_reset_postdata()
después de tu bucle while
:
endwhile;
wp_reset_postdata();
endif;
Esto asegurará que, después de que se ejecute tu shortcode, se restaure el post actual real, para que cualquier etiqueta de plantilla muestre los datos correctos.

ingresa el código aquí
texto en negrita ¿puedes probar esto?
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 archivo php content-excerpt.php y colócalo en tu tema</h1>
código de ese archivo es
<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">Leer más</a>
</article>

¿Cómo funcionará eso? get_template_part
imprimirá el contenido, no lo retornará.
