You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WordPress内联样式background-image中正确添加PHP图片路径?

解决WordPress中background-image图片路径失效问题

你的写法存在两个关键错误,导致路径无法被正确解析:

  1. PHP标签语法错误:把<?php写成了<php,WordPress无法识别这个错误标签,直接将其作为文本输出到页面中
  2. 引号嵌套冲突:style属性使用双引号包裹,同时url里也用了双引号,浏览器解析时会提前截断样式规则

正确的内联样式写法

修正语法和引号问题,同时推荐使用get_template_directory_uri()(返回模板目录URL的函数,比bloginfo()更适合嵌入属性):

<div class="slide" style="background-image: url('<?php echo get_template_directory_uri(); ?>/assets/img/slide1.jpg');"></div>
  • 用单引号包裹URL路径,避免和外层style的双引号冲突
  • get_template_directory_uri()会输出当前主题的根目录URL,确保路径始终正确

更推荐的优化方案:使用CSS类而非内联样式

内联样式不利于维护,建议将样式写到主题的style.css中:

.slide {
  background-image: url('/wp-content/themes/你的主题文件夹名/assets/img/slide1.jpg');
}

或者通过WordPress的CSS变量动态注入模板路径(更灵活,适合主题移植):

  1. 在主题的functions.php中添加:
function add_template_url_css_var() {
  $template_uri = get_template_directory_uri();
  wp_add_inline_style('your-theme-style-handle', ":root { --template-url: '$template_uri'; }");
}
add_action('wp_enqueue_scripts', 'add_template_url_css_var');
  1. 在style.css中使用变量:
.slide {
  background-image: url(var(--template-url)/assets/img/slide1.jpg);
}

内容的提问来源于stack exchange,提问作者Pszek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:01:17