WordPress shortcode strips slashes from inline style?

I’m having an issue where I’m trying to set the background image of a div using an inline style (to display a featured image from a post). The shortcode is something like:

[all-systems]

And the handling function is something like:

Read More
$markup = '';

$img = get_the_thumbnail(...); 

// if I die($img) at this point, I am getting a valid link to my image like
// http://somedomain.com/wp-content/uploads/2015/03/pic.jpg

$markup .= "<div style='background-image('" . $image . "')>...</div>";

return $markup;

The resulting markup that the shortcode spits out is correct with the exception that the /‘s in my background-image url are missing and replaced with spaces. So the background-image literally looks like:

http:  mydomain.com wp-content upload 2015 03 pic.jpg

Is this a protection that wordpress is “helping” me with? Anyway around this?

Related posts

Leave a Reply

4 comments

  1. There is an old discussion here about the “why/reasoning behind it” that doesn’t really resolve anything…

    However, what I’ve discovered, if you take out the quotes and just print the link without the quotes, it works fine.

    $markup .= "<div style='background-image(" . $image . ")>...</div>";
    

    It’s what the previous answer essentially did, using printf instead.

  2. Try this

    if ( $thumbnail_id = get_post_thumbnail_id() ) {
        if ( $image_src = wp_get_attachment_image_src( $thumbnail_id, 'normal-bg' ) )
            printf( ' style="background-image: url(%s);"', $image_src[0] );     
    }
    
    ?>>
    
  3. Check that the html preceding the inline style is correctly formed and that there are no unclosed tags. I recently had this issue with a shortcode I was writing that displayed an img tag. The url in the img src had the slashes stripped from it. The cause of this was an unclosed anchor tag. Once the anchor tag was correctly closed the img src was correctly rendered by the browser with slashes.

    For example this anchor with an unclosed href:

    <a href="http://en.wikipedia.org/>wikipedia</a>
    

    preceding an img tag will render the img src as

    http:  mydomain.com wp-content upload 2015 03 pic.jpg
    

    when viewed by Inspecting the element (tested in Chrome and Safari)

  4. The problem is related to the quotation marks

    And this is how you can solve it :

    $bg_img_url = "background-image:url('img/folder/img-name-".$variable.".jpg'); background-position:center; ";
    
    $markup .=  '<div class="class" style="' . $bg_img_url . '"></div>';
    

    You need to revert the double and single quotation marks.