Should we use get_template_part() in functions files instead of include_once?

The question:

I’m using the theme-check plugin to check my theme for errors and recommendations, I’m using get_template_part() in theme files like header.php and index.php but in functions.php I’m using include_once() theme-check is not pointing at these, it’s pointing at include_once used in a widgets.php file which is included in functions.php

my question is should we use get_template_part() instead of all include_once() and include() or just use it for getting frequently used markup only ? I know it’s only recommended to use get_template_part() but I like to follow best practices and recommendations.

thanks in advance.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Your functions.php doesn’t create output, so you should use locate_template().

Example:

locate_template( 'php/functions.nav-menu.php', TRUE, TRUE );

You’ll find this function in wp-includes/theme.php. The first parameter is the file path relative to the theme root, the second tells WordPress to load it (or not), and the third to load it just once.

Now a child theme can override the file by just placing a file with the same name to the same place in its own theme root.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment