Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have seen WordPress developers use two different methods for loading custom widgets from the functions.php file.

The first:

include("functions/my-custom-widget.php");

The second:

require_once(dirname(__FILE__) . "/functions/my-custom-widget.php");

Which one of these methods is more efficient. I'm particularly interested in performance if there is a difference at all. Does the require_once follow better 'best practices' ?

I'm sure there are plenty of other ways of doing this. If anyone has a better recommendation I would love to hear it.

Thanks.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

Both are acceptable but not recommended. Use locate_template() instead because a child theme can overwrite the loaded file then.

Example:

$found = locate_template( 'functions/my-custom-widget.php', TRUE, TRUE );

The first TRUE tells WordPress not only to search for the file but to load it actually. The second makes it a require_once call.

The function return the path to the located file in case you need it later. If nothing is found it returns an empty string.

share|improve this answer
    
Great. Didn't know locate_template() existed. This will come in handy. –  derekshirk Jun 28 '12 at 17:35

require_once (PHP documentation)

will check if the file has already been included, and if so, not include (require) it again.

This check will take more time. If you know what you're doing (including), then you should ditch the _once part and save time.

EDIT: you won't see the difference with only a few files. But if you don't include lots of files, you won't mess up your include/require either with a thing as simple as a WP theme, so IMHO there's no point in preventing multiple calls to the same file.

About the difference between require() and include():

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error.
In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

share|improve this answer
    
Thank you very much for clarifying. –  derekshirk Jun 28 '12 at 17:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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