i wrote a widget and i want to use category template which is located in "themename"/template-parts/content.php".

// Category.php  
while ( have_posts() ) : the_post();
get_template_part( 'content', '' );

In my widget i used $myposts=get_posts(); and i want to use this data with the content.php template for sure. But i dont know what is the proper way to pass this data.

I tried this but it didnt work.

// Widget.php
$myposts = get_posts($another_array);
foreach($myposts as $post) {  

And my template file.

Post: <?php the_title(); ?>
Comment Count: <?php echo get_comments_number(); ?>
Url: <?php echo get_permalink(); ?>

I tried like this too. But still not working.

Post: <?php the_title($post->ID); ?>
Comment Count: <?php echo get_comments_number($post->ID); ?>
Url: <?php echo get_permalink($post->ID); ?>

1 Answer 1


You need to setup postdata in order to set the $post global in order to make template tags available for this to work

foreach ( $myposts as $post ) {
    setup_postdata( $post );

        get_template_part( 'content' );

  • global $post; $gpost=$post; [YOUR CODE] $post=$gpost; If i make it like that. Is it going to be the proper way to do it right? I mean i dont want to do any mistakes about it.
    – Ajna Sarut
    May 20, 2016 at 13:08
  • Sorry for only replying now. The code in my answer should be the only code needed, the code you suggested would be unnecessary ;-) May 21, 2016 at 8:14
  • Pieter can you take a look here? [link]wordpress.stackexchange.com/questions/227624
    – Ajna Sarut
    May 24, 2016 at 10:08

Your Answer

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

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