Looking to use get_template_part() in WordPress? All you may need is to know how to call this function properly, helping you save on development time.
Calling get_template_part() in WordPress
To call the get_template_part() WordPress function you must first create the file you wish to call.
The function acts similar to the require() PHP function, helping to save on development time by not having to repeat your code multiple times in separate files.
get_template_part( 'file-to-fetch' );
This above code will fetch file-to-fetch.php within your active WordPress theme.
get_template_part( 'fallback-file', 'main-file' );
The above code will fetch fallback-file-main-file.php and if that doesn’t exist, it will fetch fallback-file.php.
get_template_part( 'content', get_post_format() );
The above code will fetch content-postformat.php for example.
Getting template parts in folders
To get template parts in folders, use the code below.
get_template_part( 'example-folder/example-file' );
This will fetch your-theme-folder/example-folder/example-file.php.
Using get_template_part() For Child Themes
To use the function with child themes, please see the breakdown of file priorities below.
get_template_part( 'fallback-file', 'main-file' );
- child-theme/fallback-file-main-file.php
- main-theme/fallback-file-main-file.php
- child-theme/fallback-file.php
- main-theme/fallback-file.php