I want to reuse code made in a template in a shortcode.
I did this in my shortcode
$args = array(...);
$posts = get_posts($args);
for ( $j=0; $j < count($posts); $j++ ) {
...
$post_id = $posts[$j]->ID;
setup_postdata($posts[$j]);
ob_start();
get_template_part( 'includes/post-formats/postbox' );
$output .= ob_get_contents();
ob_end_clean();
}
return $output;
Code in the template is something like this:
<div class="post-header span3">
<?php if(is_sticky()) : ?>
<h5 class="post-label"><?php echo theme_locals("featured");?></h5>
<?php endif; ?>
<h2 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
<?php
the_post_thumbnail( 'medium' );
?>
</div>
<div class="foo">
<?php the_content(); ?>
</div>
Well, the problem is that the title and the thumbnail don't work, the title and the thumbnail are shown wrong. Only the content is shown well (via the_content()).
$post
global.setup_postdata( $post )
wp_reset_postdata();
after your loop since you're usingsetup_postdata()
function.setup_postdata
changes the global$post
value to the current value of the custom loop. You must reset your$post
global back to main query ;-)