How to echo an image with php

24,088

Solution 1

You are already in php / echoing things out, so you do not need to use php tags:

echo '<img src="' . bloginfo('stylesheet_directory') . '/_images/project3image1.jpg">';

Solution 2

Do not mix markup with code. You are asking for troubles and it all looses readability. Use printf like this:

printf( '<img src="%s/_images/project3image1.jpg">', bloginfo('stylesheet_directory'));

But your real problem was nested quotation marks. If you use ' to delimit string boundaries, like:

'foo'

then if string content contains ' too:

'foo'bar'

it have to be escaped like this:

'foo\'bar'

otherwise your content quotation mark would be considered closing quotation for the string. Or you can use " instead:

"foo'bar"

but again - if your string content contains " then it have to be escaped:

"foo\"bar"

if string contains both " and ' then you need to escape only that one which is string delimiter, i.e.:

'foo"bar\'foo'

or

"foo'bar\"foo"
Share:
24,088
user1636968
Author by

user1636968

Updated on July 09, 2022

Comments

  • user1636968
    user1636968 almost 2 years

    I'm trying to echo an image from my '_images' folder, but if I write the following code, it is only for my website:

    echo '<img src="http://mywebsite.com/mytheme/wp-content/themes/my theme/_images/project3image1.jpg">';
    

    I've changed it to this so when someone else uses my theme, it takes them to their own website directory:

    echo '<img src="<?php bloginfo('stylesheet_directory'); ?>/_images/project3image1.jpg">'; 
    

    But there must be something wrong with this code when I put that and preview my website it gives me this error:

    Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/content/32/9825632/html/bomb/wp-content/themes/bomb/header.php on line 101
    

    I'm a php noob so it's probably an obvious mistake!