< BACK TO BLOG

How to use get_template_part passing params in WordPress

Published January 30, 2022

Have you ever needed a function that imports a template part but comes with a flag that indicates when that template should be rendered or not?

So do I. And when I started searching for a solution I found this awesome function. This way you can pass a Slider component for example, and mount it differently according the information is being passed on.

Place this code in your functions.php:

				
/**
 * Like get_template_part() put lets you pass args to the template file
 * Args are available in the tempalte as $template_args array
 * @param string filepart
 * @param mixed wp_args style argument list
 */
function hm_get_template_part( $file, $template_args = array(), $cache_args = array() ) {
    $template_args = wp_parse_args( $template_args );
    $cache_args = wp_parse_args( $cache_args );
    if ( $cache_args ) {
        foreach ( $template_args as $key => $value ) {
            if ( is_scalar( $value ) || is_array( $value ) ) {
                $cache_args[$key] = $value;
            } else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) {
                $cache_args[$key] = call_user_method( 'get_id', $value );
            }
        }
        if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) {
            if ( ! empty( $template_args['return'] ) )
                return $cache;
            echo $cache;
            return;
        }
    }
    $file_handle = $file;
    do_action( 'start_operation', 'hm_template_part::' . $file_handle );
    if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) )
        $file = get_stylesheet_directory() . '/' . $file . '.php';
    elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) )
        $file = get_template_directory() . '/' . $file . '.php';
    ob_start();
    $return = require( $file );
    $data = ob_get_clean();
    do_action( 'end_operation', 'hm_template_part::' . $file_handle );
    if ( $cache_args ) {
        wp_cache_set( $file, $data, serialize( $cache_args ), 3600 );
    }
    if ( ! empty( $template_args['return'] ) )
        if ( $return === false )
            return false;
        else
            return $data;
    echo $data;
}

You can call this function in your page like this:

 hm_get_template_part( 'components/hero-video', [ 'video_number' => 1 ,'background' => 'ContactBG.png']); 

This way you can receive several other information that will tell the component how it should be rendered.

You can build a switch statament inside the template part that will handle the logic of displaying several versions for the same component, just by changing the params passed.


Subscribe to my Newsletter

Get the latest posts delivered right to your inbox

Avatar of Author

Taiguara Andrade

Fullstack Developer and Writer at taiguaras.xyz


© 2022 taiguaras