Using get_template_part() in wordpress theme development.

get_template_part() calls some other functions and essentially has the action of doing a require(‘something.php’). Generally: get_template_part() -> locate_templates() -> load_template() -> require(‘theFoundTemplateFile.php’).

It takes two arguments. get_template_part(‘generic template file’, ‘specialized template file’). The first argument is commonly called the ‘slug’ and the second the ‘name’. No worries though.

Let’s contextualize this a little. Assume we have a file structure like this:

wp-content/themes/mytheme/themecore.php
wp-content/themes/mytheme/themecore-fullwidth.php
wp-content/themes/mytheme/themecore-nosidebar.php
wp-content/themes/mytheme/themecore-searchpage.php

wp-content/themes/mythemechild/themecore.php
wp-content/themes/mythemechild/themecore-nosidebar.php

—–

Example 1 (EX1):
And you use get_template_part(‘themecore’). This is the simplest situation. WordPress will search for the template in the child theme directory, then parent theme directory in that order, using the first template file it comes to with the right name.

It looks through these directories for ‘themecore.php’:
wp-content/themes/mythemechild/
wp-content/themes/mytheme/

WordPress finds wp-content/themes/mythemechild/themecore.php first and loads it, ignoring the other file in the parent theme.

Example 2 (EX2):
Let’s use two arguments: get_template_part(‘themecore’,’nosidebar’). WordPress searches for ‘themecore-nosidebar.php’ in the same order as in EX1.

It looks through these directories for ‘themecore-nosidebar.php’:
wp-content/themes/mythemechild/
wp-content/themes/mytheme/

WordPress finds wp-content/themes/mythemechild/themecore-nosidebar.php first and loads it, ignoring the other file in the parent theme.

Example 3 (EX3):
Still two arguments: get_template_part(‘themecore’,’fullwidth’). WordPress searches for ‘themecore-fullwidth.php’ in the child, then parent theme folders.

It looks through these directories for ‘themecore-fullwidth.php’:
wp-content/themes/mythemechild/
wp-content/themes/mytheme/

WordPress has no luck in the child theme folder, and finds wp-content/themes/mytheme/themecore-fullwidth.php and loads it.

Example 4 (EX4):
Still two arguments: get_template_part(‘themecore’,’idontexist’). WordPress searches for ‘themecore-idontexist.php’ in the child, then parent theme folders. But if it doesn’t find this appended file name, it is supposed to repeat the search without it.

It looks through these directories for ‘themecore-idontexist.php’:
wp-content/themes/mythemechild/
wp-content/themes/mytheme/

WordPress doesn’t find themecore-idontexist.php, so it searches in the same order for the base template ‘themecore.php’. It ends up using wp-content/themes/mythemechild/themecore.php.