leko leko - 3 months ago 14
PHP Question

PHP Variable not displaying image that uses bloginfo('template_directory')

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;
?>

Answer

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

<?php
     $var = '<a href="http://www.twitter.com"><img src="'. get_bloginfo('template_directory') .'/images/social/twitter.png" /></a>';
     echo $var;
?>

Also also suggest using something like this instead for child themes. http://codex.wordpress.org/Function_Reference/get_template_directory_uri

<?php
    $var = '<img class="svg " src="'. get_template_directory_uri() .'/images/social/twitter.png">'
    echo $var;
?>

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:

<?php
    // Array of social sites
    $sites = array(
        'twitter',
        'facebook',
        'instagram'
    );

    // Loop through each
    foreach($sites as $site){
        $var = '<img src="'. get_template_directory_uri() .'/images/social/'. $site .'.png">';
        echo $var;
    }
?>