ABSPATH or __FILE__?

2019-02-02 15:40发布

问题:

Can someone tell me if either of these two methods has an advantage over the other and why?

$mydir = ABSPATH.'/wp-content/themes/mytheme/images';

$mydir = dirname(__FILE__).'/images';

They can both be used to obtain and absolute path to the images directory of "mytheme" regardless of structure of whether wordpress is installed on the root directory or in a subdirectory off the root. In both cases, they are being called from the functions.php file which is located under the "mytheme" folder.

回答1:

I would personally prefer dirname() as it is always guaranteed to give me the correct result, while the ABSPATH method relies on a fixed theme path and theme name that can both change.

By the way, you can use __DIR__ instead of dirname(__FILE__).



回答2:

  • The path to the "wp-content" directory and its subdirectories can be different in a particular WordPress installation. Also, using the WordPress internal constants (such as ABSPATH) is not recommended. See the Determining Plugin and Content Directories WordPress Codex article.
  • Since PHP 4.0.2, symlinks are being resolved for the __FILE__ and __DIR__ magic constants, so take that into account.

    Bottom line: To determine the absolute path to a theme directory, I would suggest to use the get_template_directory() function which also applies filters and internally combines get_theme_root() and get_template().



回答3:

For my own projects I would choose dirname(__FILE__), also there is a new constant in PHP:

__DIR__ === dirname(__FILE__)


回答4:

ABSPATH is defined variable -> define("ABSPATH",__FILE__); if i directly use magic constant __FILE__ .it will produce same result.

In CMS ABSPATH and framework use BASEPATH is used to get root information in the form of defined variable . In the end with the help of both we get same accurate result.



标签: php wordpress