WordPress插件开发确定插件和内容目录

WordPress插件开发如何确定插件和内容目录?

在编写 WordPress 插件时,您经常需要在整个 WordPress 安装以及插件或主题中引用各种文件和文件夹。WordPress 提供了几个函数,可以轻松确定给定文件或目录的位置。请始终在插件中使用这些函数,而不是硬编码对 wp-content 目录的引用或使用 WordPress 内部常量。

WordPress 允许用户将 wp-content 目录放置在任何位置,并根据需要重命名。切勿想当然地认为插件会放在 wp-content/plugins 中,上传会放在 wp-content/uploads 中,主题会放在 wp-content/themes 中。

PHP 的__FILE__魔法常量会自动解析符号链接,因此如果 wp-contentwp-content/plugins 甚至单个插件目录是符号链接,则硬编码路径将无法正常工作。

常见用法

如果你的插件包含 JavaScript 文件、CSS 文件或其他外部文件,那么你可能需要这些文件的 URL,以便将它们加载到页面中。为此,你应该使用 plugins_url() 函数,如下所示:

plugins_url( 'myscript.js', __FILE__ );

这将返回 myscript.js 的完整 URL,例如 hao-blog.com/wp-content/plugins/myplugin/myscript.js

要将插件的 JavaScript 或 CSS 加载到页面中,您应该分别使用 wp_enqueue_script() 或 wp_enqueue_style() ,并将的结果 plugins_url() 作为文件 URL 传递。

可用函数

WordPress 包含许多其他函数,用于确定插件、主题以及 WordPress 本身中文件或目录的路径和 URL。有关每个函数的完整使用信息,请参阅各自的 DevHub 页面。

插件

plugins_url()
plugin_dir_url()
plugin_dir_path()
plugin_basename()

主题

get_template_directory_uri()
get_stylesheet_directory_uri()
get_stylesheet_uri()
get_theme_root_uri()
get_theme_root()
get_theme_roots()
get_stylesheet_directory()
get_template_directory()

网站首页

home_url()
get_home_path()

WordPress

admin_url()
site_url()
content_url()
includes_url()
wp_upload_dir()

多站点

get_admin_url()

get_home_url()

get_site_url()

network_admin_url()

network_site_url()

network_home_url()

常量

WordPress 在确定内容和插件目录的路径时使用以下常量。这些常量不应由插件或主题直接使用,但为了完整性,在此列出。

WP_CONTENT_DIR  // no trailing slash, full paths only

WP_CONTENT_URL  // full url

WP_PLUGIN_DIR  // full path, no trailing slash

WP_PLUGIN_URL  // full url, no trailing slash

 

// Available per default in MS, not set in single site install

// Can be used in single site installs (as usual: at your own risk)

UPLOADS // (If set, uploads folder, relative to ABSPATH) (for e.g.: /wp-content/uploads)

有关的

WordPress 目录:

home_url() 主页网址           https://hao-blog.com/

站点网址() 站点目录 URL      https://hao-blog.com/或https://hao-blog.com/wordpress

admin_url() 管理目录 URL       https://hao-blog.com/wp-admin

includes_url() 包含目录 URL    https://hao-blog.com/wp-includes

content_url() 内容目录 URL     https://hao-blog.com/wp-content

plugins_url() 插件目录 URL     https://hao-blog.com/wp-content/plugins

wp_upload_dir() 上传目录URL(返回数组)  https://hao-blog.com/wp-content/uploads

顶部