0

I am trying to embed a Twitch.tv live stream into an echo (so that the stream shows when online, but shows text when offline). This is my first learning experience with echos. I have it working so long as I just have text showing, but when I insert the shortcode, an iframe, or even just html to display an image I get a parse error.

Here is the code that I want to insert into the ONLINE INFO of the echo:

    <?php echo do_shortcode('[embedTwitch username="CHANNELNAME" width="100%"]'); ?>

Here is the code I am trying to insert it into (specifically into the ONLINE INFO area):

    <?php $streamChannel = "CHANNELNAME";
    $json_array = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams.json?channel=$streamChannel"), true);
    if(isset($json_array['streams'][0]['channel'])) {
    echo "<div id='streamonline'>ONLINE INFO</div></div>";    
    } else {
    echo "<div id='streamoffline'>OFFLINE INFO</div>";
    }
    ?>

Both work independently of the other, but when I try to insert the stream into the variable online/offline code I get an error. Here is what I am doing that gets the error:

<?php $streamChannel = "CHANNELNAME";
$json_array = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams.json?channel=$streamChannel"), true);
if(isset($json_array['streams'][0]['channel'])) {
echo "<div id='streamonline'><?php echo do_shortcode('[embedTwitch username="CHANNELNAME" width="100%"]'); ?></div></div>";
} else {
echo "<div id='streamoffline'>OFFLINE INFO</div>";
}
?>

2 Answers2

3

you're already inside PHP tags, so all you need to do is call the function & concatenate:

echo "<div id='streamonline'>".do_shortcode('[embedTwitch username="CHANNELNAME" width="100%"]')."</div></div>";
Rob G
  • 592
  • 4
  • 18
  • This worked perfectly. Thank you so much. I appreciate it a great deal. I'm going to read about concatenation next. – sparklypony Dec 06 '15 at 18:28
1

What you're trying to do is something called string concatenation. You need to echo a single string, which is the result of two strings put together. PHP has no concept of an "echo inside an echo".

Here is a simple example:

$hello = 'Hello ';
$world = 'world!';

echo $hello . $world; // Hello world!

The period . in between the two variables is called the string concatenation operator.

Since the result of the do_shortcode() function is a string, you just need to make sure it is added in between the rest of your string. Here's your code modified to do that:

<?php

$streamChannel = "CHANNELNAME";
$json_array = json_decode(file_get_contents("https://api.twitch.tv/kraken/streams.json?channel=$streamChannel"), true);

if (isset($json_array['streams'][0]['channel'])) {
  echo "<div id='streamonline'>" . do_shortcode('[embedTwitch username="CHANNELNAME" width="100%"])' . "</div>";
} else {
  echo "<div id='streamoffline'>OFFLINE INFO</div>";
}

?>
Aken Roberts
  • 13,012
  • 3
  • 34
  • 40