LoginSignup
27
10

WordpressでCSSにbackground-imageに指定した画像が表示されない問題

Last updated at Posted at 2019-12-04

物凄くくだらないことだったが意外と答えにたどり着くまでに時間がかかってしまったので自分みたいな人はいないと思うがメモ

前提としてディレクトリ構成と表示したいsample.jpgのパスは以下の通り。

wp-content/themes/sample_theme

sample_theme
 -index.php
 -style.css
 -images
  sample.jpg

表示したいimgタグのsrc属性を指定する際はこんなwordpressのタグをつけると、テンプレートディレクトリを出力してくれる。
※階層がテーマフォルダ/img/画像ファイルの場合

index.php

<img src="<?php bloginfo('template_directory'); ?>/images/sample.jpg" alt="sample">

しかし、CSSファイルにて純粋なフォルダパスを指定しても画像を読み込んでくれない。
上記に倣って下のようにwordpressタグのを使用してもこれまたうまくいかない。
初歩的すぎるが故に情報も見つからず地味に悩んだ。

style.css
/*ダメ*/
background-image: url("<?php bloginfo('template_directory'); ?>/images/sample.jpg");

wordpress上でstyle.css以外のCSSを読み込むために使うでもダメ。

style.css
/*ダメ*/
background-image: url("<?php echo get_template_directory_uri(); ?>/images/sample.jpg");

結論:wordpressの特殊なタグは必要なく、テンプレートフォルダの直下にあるimageフォルダを直接指定するだけで読み込んでくれた。(簡単過ぎて恥ずかしい...)

style.css
/*OK!!*/
background-image: url("images/sample.jpg");
27
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
10