Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

JAKZ AIZZAT
JAKZ AIZZAT
7,813 Points

How to replace src image in css with php ( wordpress )

This is my css code

#one:before {
        background-image: url("../images/banner.jpg");
        background-position: top right;
        background-repeat: no-repeat;
        background-size: cover;
        content: '';
        display: block;
        height: 15em;
        width: 100%;
    }

I'm trying to practice my wordpress skill by convert static html to wordpress theme but I'm stuck to replace background-image in css file.

Usually we just replace it with

<?php bloginfo('template_directory'); ?> /images/banner.jpg

but it doesn't work on css file.

So,how to fix it?

This image only selector for #one:before .

If its image only select #one ,i have done it in html file.

2 Answers

Hi Jakz

Question: Do you edit the css file directly or do you overwrite the old one by adding an additional css file?

By the estimation that your style.css file is in your theme root and is containing this lines of css, then you would simply add a folder "images" in your theme root and add the banner.jpg there.

To change the styles of your page using PHP there are few ways you could go. You could:

a) Conditionally add CSS classes to HTML elements that to change the style

b) You can also change the style attribute by doing something like:

<div style="background-image: '<?php bloginfo('template_directory'); ?>/images/banner.jp';">
</div>

Hope that helps!

JAKZ AIZZAT
JAKZ AIZZAT
7,813 Points

I like the b) method but how to add :before on html element in php stylesheet?

My target is

#one:before{


}

To target the before pseudo element you will have to go with option A.

Here is a sample of what you can do:

<style>

  #one:before {
      background-image: 'example1.png';
  }

  #two:before {
      background-image: 'example1.png';
  }

</style>

<div id="one <?php if(true){ echo 'two'; }?>"></div>

This should allow you to dynamically alter styles with PHP and HTML classes. Watch out for specificity battles with your css though!