plugin_dir_path()

 

File: wp-includes/plugin.php

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

参数:plugin_dir_path( string $file )

The filename of the plugin (__FILE__).

(string)包含插件的目录的文件系统路径。

$file

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

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.

  1. 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/
    
    

  3. 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.

  4. 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/
    

  5. 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' );
    }

  6. 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' );
    }
    

You must log in before being able to contribute a note or feedback.

76.92% (10) 次Baidu访问
23.08% (3) 次Sogou访问
  • 蜘蛛:Baidu,10次,更新时间:2019-05-20 02:42:31
  • 蜘蛛:Sogou,3次,更新时间:2019-05-14 02:55:00

参与评论