問題描述

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