I have a javascript function that creates an array and fill it with the title and content of WordPress posts. In other words, I try to put the result of get_the_content() and get_the_title() in a javascrip array using the loop, and display them in a separate div.
The problem is that the result of get_the_content() dont appear in the div. not like with get_the_excerpt() or get_the_title() which both of them are correctly stored in javascript variable and correctly displayed in the div after onclick event.
The code:
<script type="text/javascript">
function initialize(str) {
<? echo 'var topics = [';?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php $title=get_the_title();?>
<?php
echo "['";
echo $title;
echo "',";
$content=get_the_content();
echo $content;
echo "],"; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php echo '];'; ?>
for (i = 0; i < topics.length; i++)
{
if(topics[i][0]==str) {
document.getElementById("id").innerHTML = locationsmee[i][1];
}
}
Thanks in advance
You’re correctly adding quotes for the title, but not for the content. You’re almost certainly getting JavaScript errors when you try the results.
You should probably also make sure that the content strings don’t contain quotes, because that would also cause errors (and would constitute a possible XSS vector, depending on where the content comes from). The simplest way to do that is to use a JSON encoding facility.