Don’t you find it tedious to repeat block of codes in different parts of your web project? Think of a scenario where you’re developing a feature-rich blog and on each page, you need to display the website’s header and footer. It’s neither efficient nor maintainable to have duplicate codes throughout your project. This is where the function ‘get_template_part()’ can become your handy toolkit for handling generic HTML structures in your WordPress theme development tasks. This function is a powerful tool for compartmentalizing portions of your WordPress themes and reusing them across various parts of your website.
Let’s say, for instance, you’re enhancing your blog’s theme. You plan to stick a neat special offer section on various pages, and you want it to be easy to update site-wide. By using ‘get_template_part()’, you can isolate this section into a separate template for convenience — tweaking your special offer then becomes a painless, one file affair. This illustrates how crucial template parts can be in helping you achieve a neater, DRY (Don’t Repeat Yourself) friendly code base, leading to a better-structured and more maintainable project. By knowing when and where to use ‘get_template_part()’, you can simplify your web development process and save ample time for testing, debugging, or sipping your favorite brew.
Syntax
get_template_part( $slug, $name, $args ); |
Parameters
$slug
(required): A string that represents the slug name for the generic template. It is used as a prefix in generating the template file name.$name
(optional): A string or null value that represents the specialization of the template. If provided, it appends the name to the template file name for more specific customization.$args
(optional): An array of additional arguments to be passed into the included template.
Return Value
This function returns false if no matching template is found, otherwise it includes and displays the found template file within your theme.
How it works
<?php | |
/** | |
* Main function for returning products, uses the WC_Product_Factory class. | |
* | |
* This function should only be called after 'init' action is finished, as there might be taxonomies that are getting | |
* registered during the init action. | |
* | |
* @since 2.2.0 | |
* | |
* @param mixed $the_product Post object or post ID of the product. | |
* @param array $deprecated Previously used to pass arguments to the factory, e.g. to force a type. | |
* @return WC_Product|null|false | |
*/ | |
function wc_get_product( $the_product = false, $deprecated = array() ) { | |
if ( ! did_action( 'woocommerce_init' ) || ! did_action( 'woocommerce_after_register_taxonomy' ) || ! did_action( 'woocommerce_after_register_post_type' ) ) { | |
/* translators: 1: wc_get_product 2: woocommerce_init 3: woocommerce_after_register_taxonomy 4: woocommerce_after_register_post_type */ | |
wc_doing_it_wrong( __FUNCTION__, sprintf( __( '%1$s should not be called before the %2$s, %3$s and %4$s actions have finished.', 'woocommerce' ), 'wc_get_product', 'woocommerce_init', 'woocommerce_after_register_taxonomy', 'woocommerce_after_register_post_type' ), '3.9' ); | |
return false; | |
} | |
if ( ! empty( $deprecated ) ) { | |
wc_deprecated_argument( 'args', '3.0', 'Passing args to wc_get_product is deprecated. If you need to force a type, construct the product class directly.' ); | |
} | |
return WC()->product_factory->get_product( $the_product, $deprecated ); | |
} |
- The
get_template_part
function triggers a pre-hook event called “get_template_part_{$slug}” by callingdo_action
. This allows developers to run custom logic before loading a specific template part. - It initializes an empty array called
$templates
. - If a
$name
parameter is provided, it appends"-{$name}.php"
to the$templates
array. This allows you to have specialized templates with unique names within your theme directory. - It then adds “{$slug}.php” – representing the generic template file – to the end of the
$templates
array. - The
get_template_part
function triggers another pre-hook event called “get_template_part” by callingdo_action
. This hook allows developers to perform any additional operations before attempting to locate and load the actual template files. - It uses the
locate_template
function to locate the template files in the theme directory, based on the order specified in the$templates
array. If a template file is found, it will be included and displayed. - If no matching template is found, the function returns false.
Note: Template files are commonly located in the theme directory’s root or within a subdirectory. The get_template_part
function follows a specific naming convention for finding template files based on the given $slug
and optional $name
.
Usage
Example 1: How to Pass Parameters into get_template_part
Suppose you want to include a template file called content
with some custom data in your plugin. You can use the get_template_part
function to achieve this. It allows you to pass parameters that can then be used inside the included template file. Here’s how you can do it:
<?php | |
// Set the parameters for the template | |
$data = [ | |
"name" => "John Doe", | |
"age" => 30, | |
]; | |
// Include the template file and pass the parameters | |
get_template_part("content", null, $data); |
In this example:
- We set an array of parameters called
$data
, which contains a name and age. - We call the
get_template_part
function, passing'content'
as the slug to indicate the template file we want to include,null
as the name because we don’t need to specify any specific variation of the template, and$data
as the arguments parameter. - Inside your template file (
content.php
), you can access these parameters using variables like$name
and$age
. For example:
<?php | |
// Inside content.php | |
echo 'Hello, my name is ' . $args['name'] . ' and I am ' . $args['age'] . ' years old.'; |
This will include the content.php
template file with the provided parameters, dynamically displaying values based on your custom data.
Example 2: How to Replace include get_home_template()
with get_template_part
Let’s say you’re developing a custom theme and want more control over including files for displaying your home page. Instead of using include get_home_template()
, which limits customization options, you can utilize get_template_part
for better flexibility and maintainability. Here’s an example:
<?php | |
// Inside your theme's functions.php file | |
// Hook into the 'home_template' action to replace get_home_template() | |
function replace_home_template() | |
{ | |
// Your custom logic to determine the template slug or name | |
$template_slug = "custom-home"; | |
// Include the template part with the provided slug | |
get_template_part($template_slug); | |
} | |
add_action("home_template", "replace_home_template"); |
In this example:
- We define a custom function
replace_home_template
that will be hooked into thehome_template
action, allowing us to replaceget_home_template()
with our own logic. - Inside this function, we can implement any custom logic required to determine the appropriate template slug or name. Here, we set
$template_slug
as'custom-home'
, but you can change it according to your needs. - We call
get_template_part
with the$template_slug
variable passed as the slug parameter. This will include the template file namedcustom-home.php
. - By hooking our custom function into
home_template
, wheneverget_home_template()
is called, it will instead execute our code and include our custom template file.
With this approach, you have full control over your home page template and can easily adapt it by modifying or adding different variations of custom-home.php
.
Example 3: How to Replace include_once $file;
with get_template_part
Suppose you’re working on a child theme and want to include a reusable file in multiple templates without directly using PHP’s include_once
statement. You can utilize the power of get_template_part
for better code organization and reusability. Let’s see an example:
<?php | |
// Inside your child theme's functions.php file | |
// Hook into a relevant action, e.g., 'after_header' | |
function include_custom_file() | |
{ | |
// Set the file path to include | |
$file = get_stylesheet_directory() . "/includes/custom-file.php"; | |
// Include the file using get_template_part | |
get_template_part("includes/custom-file"); | |
} | |
add_action("after_header", "include_custom_file"); |
In this example:
- We define a custom function
include_custom_file
that will be hooked into theafter_header
action, indicating where in the theme’s output hierarchy we want to include our custom file. - Inside this function, we set
$file
as the path to our reusable file (custom-file.php
) usingget_stylesheet_directory()
to ensure a child theme compatibility. - Instead of directly using
include_once $file;
, we utilizeget_template_part
with the slug'includes/custom-file'
. This will automatically search and include the appropriate template file based on WordPress template hierarchy rules. - By hooking our custom function into the desired action, you can control when and where the file is included within your theme.
Using get_template_part
, you can easily include reusable files without worrying about duplications or complex file paths, making your code more organized and maintainable across various templates in your child theme.