The proper way to include/require PHP files in WordPress

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?

Topic include theme-development themes Wordpress

Category Web


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/


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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.