Search code examples
phpcsswordpressbackground-image

Setting an element's background image via CSS from a value in a PHP variable


Is there a way of using a php variable to manipulate css?

I'd like to add an image chosen by a user in a wordpress post (featured image) to the background of a specific div. I know how to mix php and html but, is there a way of doing the same with css?

I'm getting the image with:

$img = get_the_post_thumbnail_url($post_id, 'mySize');

Solution

  • Well, you already know how to mix PHP and HTML, right? Then you just do the same, but creating a <style> element in <head>. You put your CSS in this element. Something like this:

    <head>
        <style>
            div#myDivId { background-image: url("<%= $img %>"); }
        </style>
    </head>