問題描述

我需要獲取主題目錄的 URL 以引用主題的 image / headers 目錄中的影像。 PHP 如何完成?

最佳解決方案

此功能將返回主題目錄 URL,以便您可以在其他功能中使用它:

get_bloginfo('template_directory');

或者,此功能將回顯瀏覽器的主題目錄 URL:

bloginfo('template_directory');

因此,主題 images/headers 資料夾中的影像的示例將是:

<img src="<?php bloginfo('template_directory'); ?>/images/headers/image.jpg" />

次佳解決方案

什麼 @埃曼說,有一個警告。 Eric 是一般的方法,bloginfo()get_bloginfo()的功能如何工作,以及如何透過引數'template_directory'來獲取 (大多數) 主題所需的值。

然而,有一個警告,並且警告是與較新的兒童主題。如果您使用的是一個子主題,那麼'template_directory'可能不是你想要的,除非你真的試圖引用父主題目錄中的一個影像。相反,孩子的主題你可能想要透過 stylesheet_directory(我知道,我知道,名字不告訴你他們是什麼,但嘿,這只是這樣的方式!) 借用一些從 Eric 的回覆使用 stylesheet_directory 將看起來像這個 (我縮短了例子,所以它不會包裝):

<img src="<?php bloginfo('stylesheet_directory'); ?>/images/header.jpg" />

為了說明這一點,我寫了一個快速的獨立檔案,您可以將其作為 test.php 放在您的網站的根目錄中,並執行以檢視它的輸出。首先執行一個像 TwentyTen 這樣的常規主題,然後執行一個小題材:

<?php
/*
* test.php - Test the difference between Regular and Child Themes
*
*/

include "wp-load.php";

$bloginfo_params = array(
    'admin_email',
    'atom_url',
    'charset',
    'comments_atom_url',
    'comments_rss2_url',
    'description',
    'home',
    'html_type',
    'language',
    'name',
    'pingback_url',
    'rdf_url',
    'rss2_url',
    'rss_url',
    'siteurl',
    'stylesheet_directory',
    'stylesheet_url',
    'template_directory',
    'template_url',
    'text_direction',
    'url',
    'version',
    'wpurl',
);

echo '<table border="1">';
foreach($bloginfo_params as $param) {
    $info = get_bloginfo($param);
    echo "<tr><th>{$param}:</th><td>{$info}</td></tr>";
}
echo '</table>';

如果您注意到您可能會注意到,您可以透過以下方式傳遞給 bloginfo()get_bloginfo(); 研究下面的程式碼和截圖的想法。

看一下螢幕截圖,您可以看到 stylesheet_directory 為常規主題返回與'template_directory'相同的東西,但返回與孩子主題所需的值相同的值。

For clarity on this screenshot, wp30.dev is a domain that runs only on my local computer. It is currently an instance of WordPress 3.0.1 and it is configured at 127.0.0.1 (same as localhost) on my laptop and I use it for testing ad-hoc examples like this. I used VirtualHostX as a convenience on the Mac OS X to help me set up those private non-routable .dev domains but anyone can do it manually by editing the computer’s hosts file and the ? httpd.conf file.

順便說一句,如果你不熟悉兒童主題,那裡有兩個可能有幫助的 WordPress 答案:

第三種解決方案

主題的整體結構建立在兩個選項之上 – template(控制父主題資料夾 namre) 和 stylesheet(儲存子主題資料夾 namr) 。如果沒有使用小孩主題,這些都是一樣的。

要具有過濾器的靈活性,而不是直接訪問選項,因此有相應的 get_template()get_stylesheet()

現在唯一缺少的是將這些與主題資料夾位置相結合。這可以用 get_theme_root_uri()完成,再次方便地包裝在 get_template_directory_uri()get_stylesheet_directory_uri()中。

 [get_]bloginfo()template_directorystylesheet_directory 引數只是包裝這些,沒有什麼理由使用它。我會說透過說引數說明目錄 (通常與本地路徑有關),但是返回 URL 是令人困惑的。

Sumary:

  • 使用 get_template_directory_uri()僅引用或父主題
  • 僅使用 get_stylesheet_directory_uri()或兒童主題

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。