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?

2

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';

Leave a Reply

Your email address will not be published. Required fields are marked *