I would like to create a shortcode that displays the last 3 posts to any page….

It should be laid out like this

Title

Excerpt…Read more

I’ve added this code in function.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\">Read more</a>";

  endwhile; endif;

  return $html;
 }
 add_shortcode( 'recent', 'my_recent_post' );

and it works, except now my homepage shows the 2 posts as desired in a division, but the problem is below the content, ie, below the division with the shortcode, it shows the entire 2nd article (see image).

Any suggestions?

the problem

2 Answers
2

Add wp_reset_postdata() after your while loop:

        endwhile;
    wp_reset_postdata();
endif;

This will ensure that, after your shortcode runs, the actual current post is restored, so that any template tags display the right data.

Leave a Reply

Your email address will not be published. Required fields are marked *