Why can I not use setup_postdata($post) in the sidebar?

I have created a function that takes one parameter – post type, and will output each posts with some html and title, content etc within that. However, I want to be able to use functions associated with $post, especially the_excerpt. However, when I try to use my function in my sidebar php widget, it simply outputs the main page’s title and content, not the custom queries post info.

If I run the function in the page, it works fine though, and echos out the custom queries’ post details. You may ask why I don’t just put this in the sidebar, well it’s too messy and I’ll be reusing it with different custom posts, so I thought I’d write a function.

MY function:

function myRecentPosts($postType){
     wp_reset_postdata();
       $args = array( 'post_type' => $postType,'posts_per_page' => 3);
       $recentPosts = get_posts( $args );

       foreach($recentPosts as $post){
          setup_postdata($post);  ?>                  
        <article>
          <h1><?php the_title();?></h1>
          <?php the_excerpt();?>
        </article>

     <?php 
      }
   wp_reset_postdata();

}

2 Answers
2

Your function works in your page template but not in the sidebar because at the point that your template is processed, $post already contains the post that has been loaded for the page.

I tried your code and, just like Michael said, all I needed to add was the global declaration of $post inside the function, and it displayed the posts exactly as you intended:

function myRecentPosts($postType){
     wp_reset_postdata();
       $args = array( 'post_type' => $postType,'posts_per_page' => 3);
       global $post; 
       $recentPosts = get_posts( $args );

       foreach($recentPosts as $post){
          setup_postdata($post);  ?>                  
        <article>
          <h1><?php the_title();?></h1>
          <?php the_excerpt();?>
        </article>

     <?php 
      }
   wp_reset_postdata();

}

Leave a Comment