问题描述

Determining Plugin and Content Directories 的 WordPress 文档规定:

WordPress makes use of the following constants when determining the path to the content and plugin directories. These should not be used directly by plugins or themes, but are listed here for completeness.

它继续在主题和插件开发人员不应该使用的常量中列出 WP_CONTENT_DIRWP_PLUGIN_DIR,大概是因为这样:

WordPress allows users to place their wp-content directory anywhere they want, so you must never assume that plugins will be in wp-content/plugins, or that uploads will be in wp-content/uploads, or that themes will be in wp-content/themes.

Mark Jaquith 也是 comments here,那些常量不应该被使用:

Don’t use WP_PLUGIN_URL or WP_PLUGIN_DIR — plugins might not be in the plugins directory.

那么,引用插件的完整路径,wp-content 和主题文件夹的接受方式是什么,而不使用这些常量?

作为一个简单的例子,要输出所有安装的插件的完整路径,我可以这样做:

<?php
$plugins = get_plugins();

foreach ($plugins as $file => $details) {
    echo WP_PLUGIN_DIR . '/' . $file . '<br>';
}

其中产生如下清单:

/var/www/wp-content/plugins/akismet/akismet.php
/var/www/wp-content/plugins/debug-bar/debug-bar.php
/var/www/wp-content/plugins/hello.php

(如果我正在编写一个插件以允许用户有选择地将插件作为站点备份的一部分进行归档,我可能会这样做) 。

如果使用 WP_PLUGIN_DIR 是错误的,建议的替代方案是什么?没有相当于 wp_upload_dir()的插件,主题和 wp-content 文件夹,我可以找到,这引用潜在的漫游主题和插件根目录有问题。

最佳解决方案

参考文件在当前路径或更深的嵌套

引用当前路径

plugin_dir_path( __FILE__ )."further/nesting/here.css";

它在插件和主题中工作。

在插件中引用 URl /URi

要指向插件或主题文件,请使用

plugins_url( "path/to/file", __FILE__ );

这只适用于插件

wp-admin 文件夹中引用 URl /URi

始终指向 admin_url( 'some/path' ); 。还有 get_admin_url()

参考 wp-includes 文件夹中的 URl /Uri

将它们指向 includes_url( 'some/path' );

相对于网站的 UR1 /URi

home_url( 'etc' );get_home_url()。类似于 get_site_url()site_url()。那么还有 network_home_url()。你有 network_admin_url()

wp-content 或重命名的目录

您可以重新定义 wp-content 文件夹名称。因此您可以使用 content_url()

如何获取插件文件夹的 url?

If using WP_PLUGIN_DIR is wrong, what is the suggested alternative?

只需使用 plugins_url(),无需任何参数。

如果你使用它插件,它也适用于 MU 插件。

编辑#1 如果您对当前插件的路径感兴趣,请使用 plugin_basename();

编辑#2 如果您对所有广泛的活动插件感兴趣,请使用 wp_get_active_network_plugins();

如果您不在多站点,请使用 wp_get_active_and_valid_plugins(); 。这将考虑多站点/网络。请记住,如果您不是在多站点,而是获得了 sunrise.php 下降,这将考虑到这一点。

您也可以通过 get_option( 'active_plugins' ); 检索它们,这是不推荐的,因为它不会考虑过滤器和插件验证,这在几次发生。


进一步阅读

这个列表一直在继续。有关更多信息,请查看 QueryPosts.com 上的搜索结果。

本文绝对介绍所有路径。

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。