In the following examples, I assume you are using composer and a child theme might be enabled or not.
- Use this method if you want to include a file within a theme and want to ensure the parent theme's directory is used even if a child theme is enabled:
require get_template_directory() . '/vendor/autoload.php';
- Or use this method if you want to include a file within a theme and don't mind whether the parent theme's directory is used or the child theme's directory is used if a child theme is enabled:
require get_stylesheet_directory() . '/vendor/autoload.php';
- And lastly, use this method if you want to include a file within a plugin:
require __DIR__ . '/vendor/autoload.php';
Be careful with the last method because the magic constant __DIR__
will have a different value depending on the directory in which your php file is located.
Note that there's no benefit to using the plugin_dir_path()
function as it is just a wrapper to the trailingslashit()
function.
The documentation says:
The “plugin” part of the name is misleading – it can be used for any file, and will not return the directory of a plugin unless you call it within a file in the plugin’s base directory.
See https://developer.wordpress.org/reference/functions/plugin_dir_path/ for more details.
Also note that using include
is poor practice because a missing file will only raise a warning. Always use require
instead, because a missing file will raise a fatal error and won't stay unnoticed.