5

I've been reading about the new functions for referencing theme location added in v4.7.

I read through the trac ticket. I understand why they created these functions and the benefit of get_theme_file_path() for use in child themes. But aside from verbal clarity is there a specific reason to use get_parent_theme_file_path() over get_template_directory() when referencing files in the parent theme?

0

1 Answer 1

4

Is there a specific reason to use get_parent_theme_file_path() over get_template_directory()

Yes. This new function comes with a filter

  • Filter parent_theme_file_path
  • And argument to the file path

If you take a look at the get_parent_theme_file_path() source, it's just returning get_template_directory() with extra functionality like if a file is given as an argument to the get_parent_theme_file_path it returns path to the file and it also comes parent_theme_file_path filter which is very good to override.

get_parent_theme_file_path is introduced for consistency and to allow child themes to override easily. I don't see any point not to use this instead of get_template_directory.

I wrote a post on these functions, that can be helpful.

Use case:

Suppose you are including a file in the theme using get_template_directory like the following.

include(get_template_directory().'/inc/bk.php'); /*../themes/bk-theme/inc/bk.php */

and if you want to override bk.php in the child theme it's not possible

If you include the same file with the new function

include(get_parent_theme_file_path('inc/bk.php')); /*../bk-theme/inc/bk.php */

You can easily override this file inclusion in the child theme using parent_theme_file_path like the following

add_filter('parent_theme_file_path','bk_257597_parent_theme_file',10,2);
function bk_257597_parent_theme_file($path,$file){
 if('inc/bk.php' == $file) {
  //do something
  $file = 'my-file';
  $path = 'my-path'.$file;
 }
 return $path;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.