Wordpress主题中的相对图像链接

时间:2013-06-06 16:46:01

标签: html css wordpress wordpress-theming

我理解CSS相对于它自己的位置获取图像但是我如何在Wordpress主题中以相同的方式执行此操作?

方案: 我的标题右侧有一个搜索框。搜索框附带了Twentyeleven Wordpress主题,并有以下css:

background: url(images/Search-Button.jpg) no-repeat;

它渲染出位于themes文件夹内的images文件夹中的背景图像。 它在这里找到了图像:

C:\wamp\www\wordpress\wp-content\themes\twentyeleven\images\Search-Button.jpg

现在,我想在它旁边添加一个徽标,所以我将它添加到主题的header.php中:

<div id="Title_logo">
    <img src="images/Logo.png" />
</div>

但它不能成功渲染图像,因为它没有在"...\wp-content\themes\twentyeleven\images\Logo.png"(与Search-Button.jpg相同的目录)中查找图像。

而是结果图片 src 是: C:\瓦帕\ WWW \图像\ Logo.png

并报告未找到图像。

背景图片是如何工作的?

或者至少有人能告诉我正确的方法,并解释为什么这不起作用?

即使重命名主题文件夹,我也希望它能够正常工作。

4 个答案:

答案 0 :(得分:5)

你必须这样做;

<div id="Title_logo">
    <img src="<?php echo get_template_directory_uri(); ?>/images/Logo.png" />
</div>

如果您在另一台服务器上安装主题,它也会起作用。 请参阅:http://codex.wordpress.org/Function_Reference/get_template_directory_uri#bodyContent

您在示例中的方式(src =“images / Logo.png”)将浏览器指向您的根文件夹,因为整个Wordpress cms是从 index.php 构建的你的根文件夹。

所以你必须告诉你的浏览器(通过php)图像在主题目录的images目录中。

css文件也会以这种方式加载,但会将其引荐来自相关文件从其存在的位置。 (主题目录)。所以在css中你可以像平时那样引用你的文件,但是从theme-docs(php)你必须在你的路径中使用特殊的Wordpress函数,因此函数:get_template_directory_uri();

get_template_directory_uri documentation

答案 1 :(得分:1)

background-image有效,因为它位于模板的样式表文件中。所以它花了模板文件夹的基础来寻找图像。

但是当你使用<img src="images/Logo.png" />时,它正在查看网站的基础。 Veelen解释说您需要使用get_template_directory_uri()来获取动态当前主题文件夹路径。

答案 2 :(得分:0)

以下是我管理它的方式。

图片位于此处

\themes\twentyeleven\images\Search-Button.jpg

在您的孩子主题CSS中,它通常位于此

\themes\mytheme\style.css

然后背景图片将成为

background: url(../twentyeleven/images/Search-Button.jpg) no-repeat;

答案 3 :(得分:0)

这很容易:

简单地替换:

<div id="Title_logo">
    <img src="images/Logo.png" />
</div>

使用:

<div id="Title_logo">
    <img src="<?php echo get_theme_file_uri('images/Logo.png'); ?>" />
</div>

注意:echo get_theme_file_uri('path to your assets ');