【发布时间】:2011-03-08 22:01:00
【问题描述】:
我需要获取当前插件目录,如:
[wordpress_install_dir]/wp-content/plugins/plugin_name
(如果在插件中调用getcwd(),则返回[wordpress_install_dir],即安装的根目录。)
【问题讨论】:
我需要获取当前插件目录,如:
[wordpress_install_dir]/wp-content/plugins/plugin_name
(如果在插件中调用getcwd(),则返回[wordpress_install_dir],即安装的根目录。)
【问题讨论】:
【讨论】:
plugins_url( 'images/image_inside_plugin_folder.png' , __FILE__ )
plugin_dir_path 不一定获取插件目录,它获取作为第一个参数传递的路径的父目录。所以如果__FILE__不在插件目录下,plugin_dir_path( __FILE__ )就不会返回插件目录。见more information on plugin_dir_path
看 OP 自己的答案,我认为 OP 想要;
$plugin_dir_path = dirname(__FILE__);
【讨论】:
__DIR__,实现同样的目的。
dirname( __FILE__ ) . '/' 的等价物。其他任何东西都会损害使用它的任何插件的功能。
【讨论】:
要获取插件目录,您可以使用 WordPress 函数plugin_basename($file)。所以你可以使用它来提取插件的文件夹和文件名:
$plugin_directory = plugin_basename(__FILE__);
您可以将其与插件目录的 URL 或服务器路径结合使用。因此,您可以使用常量WP_PLUGIN_URL 获取插件目录 URL 或使用WP_PLUGIN_DIR 获取服务器路径。但是正如Mark Jaquith 在下面的评论中提到的那样,这仅在插件位于 WordPress 插件目录中时才有效。
在WordPress codex 中了解更多信息。
【讨论】:
WP_PLUGIN_URL 或WP_PLUGIN_DIR — 插件可能不在插件目录中。
$full_path = WP_PLUGIN_URL . '/'. str_replace( basename( __FILE__ ), "", plugin_basename(__FILE__) );
此页面可能会有所帮助:Determining Plugin and Content Directories
【讨论】:
试试这个:
function PluginUrl() {
// Try to use the WordPress API if possible, introduced in WordPress 2.6
if (function_exists('plugins_url'))
return trailingslashit(plugins_url(basename(dirname(__FILE__))));
// Try to find it manually... can't work if wp-content was renamed or is redirected
$path = dirname(__FILE__);
$path = str_replace("\\", "/", $path);
$path = trailingslashit(get_bloginfo('wpurl')) . trailingslashit(substr($path, strpos($path, "wp-content/")));
return $path;
}
echo PluginUrl(); 将返回当前插件 URL。
【讨论】:
从 WordPress 2.6.0 开始,您可以使用plugins_url() 方法。
【讨论】:
str_replace(site_url('/'), ABSPATH, plugins_url());
如果要获取文件中的当前目录路径,可以将魔术常量__FILE__ 和__DIR__ 与plugin_dir_path() 函数结合使用:
$dir_path = plugin_dir_path( __FILE__ );
当前目录路径:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
__FILE__ 魔术常量返回当前目录路径。
如果你想从当前目录上一级,你应该使用__DIR__这个魔法常数:
当前路径:
/home/user/var/www/wordpress_site/wp-content/plugins/custom-plugin/
$dir = plugin_dir_path( __DIR__ );
一级升级路径:
/home/user/var/www/wordpress_site/wp-content/plugins/
__DIR__ 魔术常量返回上一级目录路径。
【讨论】:
在插件的主 PHP 文件中,这仅适用于管理员:
$plugin_data = get_plugin_data( __FILE__ );
$plugin_name = $plugin_data['Name'];
【讨论】: