Loading page content into a variable in template

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) {

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

   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.

Leave a Comment