Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

}
share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

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

}
share|improve this answer
add comment

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

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

share|improve this answer
    
well it works as is above in the page tmeplate, it's just in the sidebar it doesn't work –  Nicola Oct 24 '12 at 11:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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