2

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

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.

| improve this answer | |
  • TheDeadMedic that did the trick, it resolved it for me, thanks and thank you @TBI Infotech – user54779 Jun 26 '14 at 23:48
0

enter code herestrong text can you pls try this

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>create a php file content-excerpt.php and place in your theme</h1>

code of that file is**


<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">Read more</a>
</article>
| improve this answer | |
  • How will that work? get_template_part will print the content, not return it. – TheDeadMedic Jun 27 '14 at 7:47
  • Add this function in functions.php of your theme . Then call this function on home page. I haven't tested it on my end, please check if it works for you. – TBI Infotech Jul 2 '14 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.