问题描述
我需要获取主题目录的 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.devis a domain that runs only on my local computer. It is currently an instance of WordPress 3.0.1 and it is configured at127.0.0.1(same aslocalhost) 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.devdomains but anyone can do it manually by editing the computer’s hosts file and the ? httpd.conf file.
顺便说一句,如果你不熟悉儿童主题,那里有两个可能有帮助的 WordPress 答案:
- Making the Header on the Twenty Ten Theme Less Tall?
- Customizing a WordPress Theme without Changing it?
第三种解决方案
主题的整体结构建立在两个选项之上 –  template(控制父主题文件夹 namre) 和 stylesheet(保存子主题文件夹 namr) 。如果没有使用小孩主题,这些都是一样的。
要具有过滤器的灵活性,而不是直接访问选项,因此有相应的 get_template()和 get_stylesheet()。
现在唯一缺少的是将这些与主题文件夹位置相结合。这可以用 get_theme_root_uri()完成,再次方便地包装在 get_template_directory_uri()和 get_stylesheet_directory_uri()中。
 [get_]bloginfo()与 template_directory 或 stylesheet_directory 参数只是包装这些,没有什么理由使用它。我会说通过说参数说明目录 (通常与本地路径有关),但是返回 URL 是令人困惑的。
Sumary:
- 使用 get_template_directory_uri()仅引用或父主题
- 仅使用 get_stylesheet_directory_uri()或儿童主题
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。
 
											
				 
					