On one of my custom templates, I need to do some work with the content before displaying it. Is there a way that I can load this content into a variable rather than just outputting it to the page?

This is what I've tried but it only outputs the page content, it doesn't load it into the variable.

$content = get_template_part( 'content', 'page');

2 Answers 2


You can always use the output buffering to store the printing contents in a variable.

function return_get_template_part($slug, $name=null) {

   get_template_part($slug, $name);    
   $content = ob_get_contents();

   return $content;
$content = return_get_template_part('content', 'page');

This would be most preferable to keep using the get_template_part() right now. An alternative would be to use locate_template() function but it would compromise the use the default templates.

Check implementation of get_template_part() and locate_template() you would understand.


If you want to load a template file, execute the code it contains, and save the results to a variable, you need to use php's output buffering:

get_template_part( 'content', 'page' );
$content = ob_get_contents();

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.