Sander Sander - 10 months ago 45
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">
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];
var i = Math.round((Math.random()) * info.length);
if (i == info.length) --i;
document.getElementById('infoTxt').innerHTML = info[i];
}, 5 * 1000);
$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=""><img class="flagContainer" alt="English" src="<?php bloginfo('stylesheet_directory'); ?>/img/GbFlag.png""/></a></li>
<li><a href=""><img class="flagContainer" alt="Deutsch" src="<?php bloginfo('stylesheet_directory'); ?>/img/GmFlag.png""/></a></li>
<li><a href=""><img class="flagContainer" alt="French" src="<?php bloginfo('stylesheet_directory'); ?>/img/FrFlag.png""/></a></li>
</div> <!-- end Flag Box-->
<div style="margin-bottom:25%;">
<?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 Source

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:


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