Search code examples
wordpressinheritanceparent-childchild-theming

How do I check for child theme files first using include, before going to parent theme?


I'm creating a WordPress child theme based on an existing parent theme, and I'd like to have any same-named file I put in my child theme directory take priority over the file in the parent theme directory. I thought this was how parent/child theming was set up in WP but I have hit a bump.

According to the WordPress codex on Child Themes, it says:

Template Files
If you want to change more than just the stylesheet, your child theme can override any file in the parent theme: simply include a file of the same name in the child theme directory, and it will override the equivalent file in the parent theme directory when your site loads.

In one of my files (header.php), there is an include that looks like this:

include get_parent_theme_file_path("folder/file.php")

Even though I have a duplicate-named-but-modified version of that file.php in my child theme, it still uses the version in my parent theme. According to the same codex, their recommendation for targeting a child theme file specifically is to use get_stylesheet_directory(), so it would look like this:

include (get_stylesheet_directory()."/folder/file.php");

I understand that the purpose of a function called "get_parent_theme_file_path()" is to ignore the parent/child relationship and just get the parent theme version, so without replacing that with a function that explicitly gets a file in my child theme (ie. get_stylesheet_directory), is there a way I can have some sort of universal get_path() function that checks for child first, if it doesn't exist, get parent version?

By the way, I read this Q&A on "get_parent_theme_file_path vs. get_template_directory", but their solution was to use parent_theme_file filters, but that isn't dynamic, and would require me to write a filter function for every child file I want it to use.

Thanks for your help.


Solution

  • Someone on wordpress.stackexchange pointed out the use of locate_template, which retrieves the name of the highest priority template file that exists.

    Searches in the STYLESHEETPATH before TEMPLATEPATH and wp-includes/theme-compat so that themes which inherit from a parent theme can just overload one file.