2

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');
4

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.

1

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:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.