返回介绍

plugin_dir_path()

发布于 2017-09-11 09:54:53 字数 3700 浏览 904 评论 0 收藏 0

plugin_dir_path( string $file )

Get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in.


description


参数

$file

(string) (Required) The filename of the plugin (__FILE__).


返回值

(string) the filesystem path of the directory that contains the plugin.


源代码

File: wp-includes/plugin.php

function plugin_dir_path( $file ) {
	return trailingslashit( dirname( $file ) );
}

更新日志

Versiondescription
2.8.0Introduced.

More Information

It is a wrapper for trailingslashit( dirname( $file ) );.

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.


相关函数

Uses

  • wp-includes/formatting.php: trailingslashit()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 6You must log in to vote on the helpfulness of this note Contributed by Codex

    Including all PHP files from a plugin sub folder and avoiding adding a unnecessary global just to determine a path that is already available everywhere just using WP core functions.

    
    foreach ( glob( plugin_dir_path( __FILE__ ) . "subfolder/*.php" ) as $file ) {
        include_once $file;
    }
    
    
  2. Get the directory of the current file:

    
    $dir = plugin_dir_path( __FILE__ );
    // Example: /home/user/var/www/wordpress/wp-content/plugins/my-plugin/
    
    

    If you want the get the path one level up from the current dir, you can do

    
    //current path: /home/user/var/www/wordpress/wp-content/plugins/my-plugin/
    $dir = plugin_dir_path( __DIR__ );
    //$dir is set to /home/user/var/www/wordpress/wp-content/plugins/
    

    Conditional loading

    It is sometimes efficient to conditionally load files, e.g., admin-only (or even by specific admin screen):

    if ( is_admin() ) {
        include_once( plugin_dir_path( __FILE__ ) . 'includes/admin-functions.php' );
    } else {
        include_once( plugin_dir_path( __FILE__ ) . 'includes/front-end-functions.php' );
    }

    Define path constant

    For calling numerous files, it is sometimes convenient to define a constant:

    define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
    include( MY_PLUGIN_PATH . 'includes/admin-page.php');
    include( MY_PLUGIN_PATH . 'includes/classes.php');
    // etc.
    
    if ( is_admin() ) {
        include_once( plugin_dir_path( __FILE__ ) . 'includes/admin-functions.php' );
    } else {
        include_once( plugin_dir_path( __FILE__ ) . 'includes/front-end-functions.php' );
    }
    

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文