Yogesh Chauhan's Blog

How get_template_part helps write reusable code in WordPress?

in WordPress on July 25, 2021

get_template_part used to load a part of a template file into the template and helps divide the large file into smaller templates.

That’s the beauty of get_template_part. What you can do is save small chunks of code in a separate folder that can be used on multiple templates and then load those reusable components.

The template is included using PHP require which lets import same file multiple times on a page.


get_template_part( $slug, $name, $args )


  • $slug is the slug name of the template and it’s a required parameter.
  • $name is name for the template, it is an optional argument. By default it’s null.
  • You can pass additional arguments using $args such as variables and values. By default an empty array will be passed.

What if the template file doesn’t exist?

Nothing will be imported in that case. There won’t be any errors either.

How to use get_template_part?

In get_template_part function, add the folder name and then the template page slug (without the .php extension).

You can have content.php or content-page.php. Both of them works!


If you have this folder structure…

|-- partials/
|   |-- content.php
|-- page.php

…then you can import the content.php from partials like this:

get_template_part( 'partials/content', 'page' );

How to pass variables via get_template_part?

        'key'   => 'value',
        'title' => 'Title',

How to get variables passed via get_template_part?

In your content.php file, you’d get the variables like this:

$key   = $args['key'];
$title = $args['title'];
//use them anywhere in your file now

If you’re not sure what variables are passed, just dump everything and go from there:

var_dump( $args );

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Alternate Style Sheets in CSSCSSHTML canvas methodsHTMLRIGHT JOIN in PostgresPostgresWindow innerHeight and innerWidth properties in JavaScriptJavaScriptHow to Make a Simple Module with a Form and Menu Link in Drupal 7.x?DrupalThe actual difference between indexOf() and search() in JavaScriptJavaScript