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

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