問題描述

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