Wordpress主题中的相对图像链接

问题描述 投票:3回答:4

我理解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:\ wamp \ www \ images \ Logo.png

并报告未找到图像。

背景图片是如何工作的?

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

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

html css wordpress wordpress-theming
4个回答
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)该图像位于theme-directory中的images目录中。

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

get_template_directory_uri documentation


1
投票

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

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


0
投票

以下是我管理它的方式。

图像位于此处

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

在你的孩子主题CSS一般,它的位置就像这样

\themes\mytheme\style.css

然后背景图像就会变成

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

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 ');

© www.soinside.com 2019 - 2024. All rights reserved.