Result Of Get_the_content() Not Correctly Displayed
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_
Solution 1:
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.
Solution 2:
I have found the full solution based on Pointy answer. to encode wordpress posts data into JSON, it can be done via one of the two codes:
<?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 ($postsas$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);
?>
Both of the codes give a JSON string which can be accessed/dispalyed via jQuery like this:
<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>
Post a Comment for "Result Of Get_the_content() Not Correctly Displayed"