I am a little bit confused about the following code:

if (is_home() ) {
echo '<div id="bg" style="background:url("assets/img/header_1.jpg");">';
} else ( is_page( 52 )) {
echo '<div id="bg" style="background:url("assets/img/header_2.jpg");">';

It is supposed to change the header background for different pages.

The code itself works, because CSS classes were imported correctly. Unfortunately "/assets/..." doesn't work so I suppose I need this function:

<?php echo get_template_directory(); ?>

How can I implement it properly inside echo?

  • Try giving full url path for image rather than relative path. Apr 20 '15 at 3:33

You can concatenate strings with the result of a php function:

echo '<div id="bg" style="background:url(' . get_stylesheet_directory_uri() . '/assets/img/header_2.jpg);">'; 

Codex: get_stylesheet_directory_uri()

  • thanks, that's exactly what I needed. However, it doesn't work. When I do this with CSS class, everything works great: <?php if (is_front_page() ) { echo '<div id="bg" class="header-bg-mainpage">'; CSS: .header-bg-mainpage {background:url("assets/img/header_1.jpg") no-repeat center center;} What function should I use then to get the directory and use *.jpg not through CSS?
    – Dandy
    Apr 19 '15 at 23:24
  • @Dandy, try using get_stylesheet_directory_uri() instead
    – pcarvalho
    Apr 19 '15 at 23:33
  • also doesn't work. I don't get it why in CSS file simple directory "assets/.." works and in header.php file not. These two files are in the same folder.
    – Dandy
    Apr 19 '15 at 23:39
  • to the frontend, it is probably checking for the example.com/assets/.. when you're on the homepage. open the devtools and see the path. I've tried the code above and i got the right path. A link to your site would help debugging.
    – pcarvalho
    Apr 19 '15 at 23:43
  • you're right! i forgot the double quotes.. :/ it was closing the style attributes.
    – pcarvalho
    Apr 20 '15 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.