While developing WordPress themes, dividing your theme into multiple re-usable templates makes everything easier. WordPress already manages templates parts like header, footer, and sidebar using special functions like get_header, get_footer, and get_sidebar. For including all other template parts that are created by the designer we are using the get_template_part function.


How to Properly Include Template Files Using get_template_part

To include a template part in your theme, the best practice is putting your template part in a folder like partials. After you put your template part in the folder you can easily include that template part using code sample below:

get_template_part( 'partials/navbar' );

When you use this function, WordPress looks for navbar.php file in the partials folder. If it can’t find that file, it doesn’t give any errors, but, simply displays nothing.


Including Template Parts Depending on Context

If you have multiple alternative templates depending on page context, you can pass the context as a second variable (string) to the get_template_part function. See it in the example:

get_template_part( 'partials/share', 'post' );

This example looks for share-post.php file in partials folder. The important thing to note here is that if it can’t find share-post.php file, it falls back to share.php file. Using this method you can easily manage your templates depending on context, post type, user capabilities or even page slug.


Conclusion

Dividing your theme into small logical parts makes things easier both for developers and also end users. Instead of making one large file for single page, you can divide it into small parts like post-header, content, share, comments, after post etc. This way your theme will be more organized, plus it will be more manageable.