How to echo an image with php

2019-05-23 09:01发布

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!

3条回答
来,给爷笑一个
2楼-- · 2019-05-23 09:16

To use the second style of code you have first to close the php tags:

    //...your php code before echoing the img

    //here you close the tag 
    ?>

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

    <?php //here you open it again

    //your rest php code...

Anywhere in your php code if you want to echo some html, just close the php tags, write your html and open php tags again. But it is better to not mix html and php a lot. Try to write all your php code at the begining of you files and after it all your html. In your php code make variables with the dynamic values and inject php code inside html to output them inside any atribute or tag content.

查看更多
老娘就宠你
3楼-- · 2019-05-23 09:34

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"
查看更多
Rolldiameter
4楼-- · 2019-05-23 09:36

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">';
查看更多
登录 后发表回答