問題描述

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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。