1

In my template file I want to include a library. I uploaded the library into my theme folder, and inside my theme folder is my custom template file. In my custom template file I have require 'OAuth2/Client.php'; but when I load a page that uses the template, it gives me this:

Warning: require(OAuth2/Client.php): failed to open stream: No such file or directory in /home/healthf0/public_html/wp-content/themes/healthfitcorpwell/single-iframe.php on line 4

Obviously the file does exist, I can see it sitting there via FTP. Why is it telling me this?

  • never use relative paths when you include php files – Mark Kaplun May 25 '17 at 16:34
4

You are seeing this error because you are requireing the file with a relative path. As @Mark Kapulun pointed out in the comments you should not use relative paths when requireing files. Instead you want to be explicit and use absolute paths.

Use get_template_directory() which returns the

Absolute path to the directory of the current theme (without the trailing slash)

In your template file the require statement will look like:

require( get_template_directory() . '/path/from/theme/root/to/file.php');

Or get_stylesheet_directory() if you are making a child theme. doc

Update:

As @Jack Johansson noted in his answer, you may also consider using require_once instead. This will protect you from errors generated by multiple inclusions of the file. See this answer for more details.

  • 2
    get_stylesheet_directory() solved my issue. thank you. – Alex May 26 '17 at 17:47
1

Yes, but use of relative paths is not allowed. You always want absolute paths. This can be done as follows:

<?php require( get_stylesheet_directory() . '/OAuth2/Client.php'); ?>

get_stylesheet_directory() will return the absolute path where style.css is located for the theme. It will NOT put the trailing / on it though.

1

You can use get_template_directory() to get an absolute path to your template's directory. For example, if your php file is located in /my-theme/OAuth2/Client.php, use:

require_once(get_template_directory().'/OAuth2/Client.php');

Remember, DO NOT use relative or access the PHP file directly for security purposes. Also, you have to use this conditional in your client.php file to make it more secure:

if ( ! defined( 'ABSPATH' ) ) {
    exit('No script rookies, please.');
}

This does not allow direct access to your PHP file.

I also would go with require_once instead of require to make sure it doesn't trigger any error if i include it somewhere else accidentally.

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.