8

I'm a new WordPress developer and recently I've been having problems (on multiple sites) with include_once and require_once for PHP files. If I include (get_theme_directory_uri() . 'subdir/file') the specified file gets included (or required, which leads to fatal errors) but if any WordPress functions are called within 'file' I get something similar to:

'Call to undefined function add_action() in /full/path/to/file'.

The apparent solution I've found is to do:

include(dirname(__FILE__) . "/subdir/filename");

Is this right or did I miss 'the WordPress way' to include files somewhere?

1
15

If you check https://codex.wordpress.org/Function_Reference/get_template_directory_uri

You will see get_template_directory_uri() returns a uri, not a server path.

You should use instead the get_template_directory() function:

include get_template_directory() . 'subdir/filename.php';

For a plugin you can use the plugin_dir_path() function:

include plugin_dir_path( __FILE__ ) . 'subdir/filename.php';
3
  • I want to note that this is mostly intended for locating paths in arbitrary plugin. Within inside of specific plugin the relative paths are known and basic PHP includes (sans any WP bits) are a normal practice. – Rarst Oct 27 '15 at 17:46
  • With Rarst comment i realized my anwser is for plugins, not themes. For themes, use get_template_directory() instead of get_template_directory_uri(). Easy! – thomascharbit Oct 27 '15 at 17:58
  • you might want to try - /subdir/filename.php? – Jon Apr 15 '19 at 8:53
12

WordPress 4.7+ introduce get_theme_file_path() functions to include file on WordPress theme.

Include like this:

include get_theme_file_path( '/subdir/filename.php' );

The advantage of using this function is on child theme you can override the parent theme file.

Reference : https://developer.wordpress.org/reference/functions/get_theme_file_path/

2
  • Exactly what I was looking for! This should be the correct answer now. – Oneezy Aug 23 '19 at 13:04
  • Exactly, WP updated the helper to do so, this is the good answer. – Maxime Culea Sep 16 '20 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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