WordPress: save `get_template_part()` to variable

This isn’t what get_template_part was for, get_template_part essentially behaves like PHP’s require function. Justin Tadlock writes a lot more about this here and also talks about a WordPress function that might be more useful to you – locate_template.

Alternatively, if you did want to hack this functionality using get_template_part, you could use template buffering:

function load_template_part($template_name, $part_name=null) {
    ob_start();
    get_template_part($template_name, $part_name);
    $var = ob_get_contents();
    ob_end_clean();
    return $var;
}

Leave a Comment