0

I am writing a shortcode plugin that displays posts according to some parameters passed into the shortcode. I have the wp_query to get the posts and now I am trying to get the markup for the posts according to the theme's template files.

In essence, get_template_part is exactly what I want... except that it directly loads the markup into the template. I want to get the markup for the content, perform a little post-processing and then return the markup for the shortcode. Essentially,

$listings = new WP_Query(...);
while ( have_posts() ) {
    $markup .= get_template_part('content', $post->post_type);
}
return $markup

Except this obviously isn't the way that get_template_part works. How do I get the markup for a post without rendering the markup into the page?

2 Answers 2

1

I couldn't figure out a WordPress way to do this and looking at the WP source, it looks like this probably will never really be possible. However, I was able to get a solution using vanilla PHP by redirecting standard output into a buffer and loading the buffer into a variable.

$listings = new WP_Query(...);
ob_start();
while ( have_posts() ) {
    get_template_part('content', $post->post_type);
}
$markup = ob_get_contents();
ob_end_clean();
return $markup
0

If you're looking for just the content from a post before it gets loaded into a template, then you're probably looking for get_the_content().

2
  • No. That isn't quite what I am looking for. Since I am using this as a shortcode, the normal functions like get_the_content don't work properly... From the docs, "Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself."
    – Jeff
    Commented Jun 13, 2014 at 20:23
  • In otherwords, I need to get the markup and return, instead of echo, which is akin to what get_the_content would do.
    – Jeff
    Commented Jun 13, 2014 at 20:24

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.