get_the_content()没有正确显示的结果
问题描述:
我有一个javascript函数,它创建一个数组,并用Wordpress文章的标题和内容填充它。换句话说,我尝试使用循环将get_the_content()
和get_the_title()
的结果放入javascrip数组中,并将它们显示在单独的div中。 问题是,get_the_content()的结果不会出现在div中。不像get_the_excerpt()或get_the_title(),它们都正确存储在javascript变量中,并在onclick事件后正确显示在div中。get_the_content()没有正确显示的结果
代码:
<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];
}
}
在此先感谢
答
你正确添加报价为标题,而不是内容。当您尝试结果时几乎肯定会发生JavaScript错误。
您应该确保内容字符串不包含引号,因为这也会导致错误(并构成可能的XSS向量,具体取决于内容的来源)。最简单的方法是使用JSON编码工具。
答
我发现基于Pointy答案的完整解决方案。
<?php
header('Content-Type: text/html; charset: UTF-8');
require('../English/The-Blog/wp-load.php');
query_posts(array('posts_per_page' => 20,));
$jsonpost = array();
$i=0;
if (have_posts()) :
while (have_posts()) : the_post();
$jsonpost[$i]["id"] = get_the_ID();
$jsonpost[$i]["title"] = get_the_title();
$jsonpost[$i]["url"] = apply_filters('the_permalink', get_permalink());
$jsonpost[$i]["content"] = apply_filters('the_content', get_the_content());
$jsonpost[$i]["date"] = get_the_time('d F Y');
$i=$i+1;
endwhile;
endif;
header('Content-type: application/json;');
echo json_encode($jsonpost);
?>
OR
<?php
define('WP_USE_THEMES', false);
require('../English/The-Blog/wp-blog-header.php');
$posts = get_posts(array(
'numberposts' => 5,
'offset' => 0,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
));
$json = array();
if ($posts) {
foreach ($posts as $post) {
$ray = array();
the_post();
$ray['id'] = $post->ID;
$ray['date'] = $post->post_date;
$ray['contents'] = $post->post_content;
$ray['title'] = $post->post_title;
$json['posts'][] = $ray;
}
}
header('Content-type: application/json;');
echo json_encode($json);
?>
这两个码的给予可接JSON字符串:以编码的wordpress帖子数据到JSON,它可以通过两个码中的一个来进行/显示通过像这样的jQuery:
<script>
jQuery(document).ready(function($){
$(".load").click(function(){
$.getJSON(
'phpscript.php',
function(data){
$('#9lessonsLinks').hide();
for (var i=0 ; i < data.length ; i++)
{
var personne = data[i];
var div_data ="<div class='box'><a>"+personne.url+"</a></div>";
$(div_data).appendTo("#9lessonsLinks");
}
$('#9lessonsLinks').fadeIn();
}
);
});
});
</script>
+1
你的数据看起来像是一个**数组**。您必须遍历数组中的项目。 – Pointy 2012-03-25 14:09:22
谢谢Pointy为快速的答案,报价问题已纠正,但问题sti我会保持。我现在正在尝试了解JSON以及如何使用它。如果没有,还有其他建议吗? – 2012-03-17 21:30:43
请再次帮助我,这将是如此宝贵。上面检查我的答案。 – 2012-03-25 13:38:11
在过去,我没有足够的repu来投票。谢谢 – 2013-04-01 02:19:49