WordPress: save `get_template_part()` to variable

In short, all I need is to make my WordPress do this

$var = get_template_part( 'loop', 'index' ); 

but, get_template_part() does not return HTML, it prints it.
I need this HTML stored in $var - do you have any ideas how to do it?


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;
}

I'm not loving Output Buffering, though +1 for even thinking of that as an option!

I think Helga was on to something, but you need to still respect the child_themes and the theme path, so use locate_template() instead (also as Simon suggested).

This works nicely, and can even be used inside a filter or (in my case) shortcode function (I wanted my shortcode to output the content within a template-style file, to separate the display layer from the logic layer).

return file_get_contents(locate_template("template-file-name.php")); // don't forget the .php!

what about?

$file = file_get_contents(STYLESHEETPATH . '/template-part.php'); 
return $file;

i'm sure there is a better way, but that seems to work for me.


If your goal is to create a shortcode with the HTML return, the example below works for me:

function funcao_produtos_filtro_ead() { 

    $html = "";

    ob_start();
    
    // LOOP DE PRODUTOS
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => '-1'
    );

    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();

            wc_get_template_part( 'content', 'product' );

        endwhile;
    }

    wp_reset_postdata();

    return '<div class="woocommerce">' . ob_get_clean() . '</div>';
    
  }

  add_shortcode('produtos_filtro_ead', 'funcao_produtos_filtro_ead');