Passing variables using get_template_part

get_template_part is famous for not letting you pass variables to the included file. There are lots of articles dealing with this issue. The suggested workaround is to use include( locate_template( 'file.php' ) ) instead.

In the end when you are using get_template_part WordPress searches for the file using the locate_template function and loads that file with the load_template.

Here is the load_template function; it is located in wp-includes/template.php.

function load_template( $_template_file, $require_once = true ) {

    global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID;

    if ( is_array( $wp_query->query_vars ) ) {

        extract( $wp_query->query_vars, EXTR_SKIP );

    }

    if ( isset( $s ) ) {

        $s = esc_attr( $s );

    }

    if ( $require_once ) {

        require_once( $_template_file );

    } else {

        require( $_template_file );

    }

}

This function is responsible for loading files and for allowing you to use the global WordPress variables you are used to.

…It also unsets all other variables.

If you don’t want to use the include( locate_template( 'file.php' ) ) workaround, you can attach the data you want to pass to the $wp_query and since WordPress makes the $wp_query avaliable to you the passed variable can be used.

$wp_query->partial = [
    'color' => 'blue',
];

get_template_part( 'parts/front-page/latest' );

To display it in the partial file call it like this:

echo $wp_query->partial['color']; // blue

It is also advisable to unset the attached data immediately after you called the get_template_part function unset( $wp_query->partial ).

Did you find this article useful, interesting or you want to chat about this topic? Send me a mail and let me know. In case you found some spelling or grammar mistakes let me know that too.