4

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

1

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();

}
0

setup_postdata($post); seems to require that $post is set as a global variable:

http://codex.wordpress.org/Function_Reference/setup_postdata

1
  • well it works as is above in the page tmeplate, it's just in the sidebar it doesn't work
    – Claire
    Commented Oct 24, 2012 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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