Sander Sander - 2 months ago 10
PHP Question

Javascript from PHP (wordpress)

I created a new WordPress theme. When I moved it into an IIS webserver it fails.

Here's my code:

<?php get_header(); ?>
<h2><?php the_title();?></h2>
<div class="infoBox" id="infoTxt">
<?php
if(get_the_title() == 'Home'){
$page = get_page_by_title( get_the_title());
$Pagecontent = apply_filters('the_content', $page->post_content);
$ContentArray = explode(";",$Pagecontent);
echo $ContentArray[count($ContentArray) -1];
<script type="text/javascript">
var info = <?php echo json_encode($ContentArray) ?>;
document.getElementById('infoTxt').innerHTML = info[1];
setInterval(function()
{
var i = Math.round((Math.random()) * info.length);
if (i == info.length) --i;
document.getElementById('infoTxt').innerHTML = info[i];
}, 5 * 1000);
</script>
<?php
}
else{
$page = get_page_by_title( get_the_title());
$content = apply_filters('the_content', $page->post_content);
$InfoboxStr = substr($content, 0, strpos($content, '@:'));
echo $InfoboxStr;
}

?>
</div><!--End InfoTxt-->
<div id="Flagbox">
<ul style="list-style-type:none;">
<li><a href="www.google.dk"><img class="flagContainer" alt="English" src="<?php bloginfo('stylesheet_directory'); ?>/img/GbFlag.png""/></a></li>
<li><a href="www.google.dk"><img class="flagContainer" alt="Deutsch" src="<?php bloginfo('stylesheet_directory'); ?>/img/GmFlag.png""/></a></li>
<li><a href="www.google.dk"><img class="flagContainer" alt="French" src="<?php bloginfo('stylesheet_directory'); ?>/img/FrFlag.png""/></a></li>
</ul>
</div> <!-- end Flag Box-->
<div style="margin-bottom:25%;">
</div>
<?php get_footer(); ?>


It is because of the JavaScript but I have some problem fixing this, I have first of all tried to echo the JavaScript, but I then got a problem with the first line of the script which is:
var info = <?php echo json_encode($ContentArray) ?>;


When I ex. tried to

Echo 'var info = ' + echo json_encode($ContentArray) ?> + ";"


I just gets an http 500-error. Do any of you have an idea of what I can try to fix my problem

Answer

If you want to use the tag, you need to close the php tag, in here:

echo $ContentArray[count($ContentArray) -1];    
        <script type="text/javascript">

So it should look like that:

?>
<script>
[..]
</script>
<?php

The best practice it that you should place the JS either in at the top or bottom of your file or in another file.