I need to store a hyperlinked image inside a variable, and then echo out that variable for my WordPress website. I find it more convenient to use bloginfo(‘template_directory’) so that I can go back and forth between local and live server.
But bloginfo(‘template_directory’) within a variable does not work, it displays nothing. But bloginfo(‘template_directory’) will work in other areas of my website. What could be the problem?
CODE A works. Notice 127.0.0.1 in the URL
<?php
$var = '<a href="http://www.twitter.com">
<img src="http://127.0.0.1/wp-content/themes/twentyfourteen/images/social/twitter.png" />
</a>';
echo $var;
?>
CODE B displays nothing. Why is the below not working? Notice below I am using bloginfo(‘template_directory’) instead of 127.0.0.1
<?php
$var = '<a href="http://www.twitter.com">
<img src="<?php bloginfo('template_directory'); ?>/images/social/twitter.png" />
</a>';
echo $var;
?>
EDIT
CODE C how to replace the word “twitter” with a variable? (I am referring to line 3 below, the word “twitter” that is located in img src)
<?php
$var = '<a href="http://www.website.com">
<img src="' . get_bloginfo("template_directory") . '/images/social/twitter.png" />
</a>';
echo $var;
?>
You need to use get_bloginfo for you want it in a var. Also no need for php tags when in a string.
http://codex.wordpress.org/Function_Reference/get_bloginfo
Also also suggest using something like this instead for child themes.
http://codex.wordpress.org/Function_Reference/get_template_directory_uri
In response to your EDIT C code block, I’m guessing you are trying to loop through some social media icon links. This is how you might do that:
Don’t use
get_bloginfo( 'template_directory' )
and for that matterget_bloginfo( 'stylesheet_directory' )
which is used for child themes. These was used in early WordPress versions. In later versions these was “replaced” with more appropriate functions.The correct functions to use is
get_template_directory_uri()
for parent themes andget_stylesheet_directory_uri()
for child themes. I would suggest that you work through these pages carefullyAs for your syntax, as explained in the other answer, you cannot use HTML and PHP in the same string without separating them. This is done using the string operators which you can go and read up on in the link provided
It seems that you need to add social media icons. If so, check out these two posts. Specially read the one that @toscho done to my question. That should help you quite a lot with a few issues
listing repeating social media buttons. Take your time on this one. This is an excellent post that helped me out big time when I just started out
Social share buttons using genericons
You can’t have PHP tags in PHP tags:
Just concatenate the strings: