Loading page content into a variable in template

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