I’m trying to display my latest 3 posts from my WordPress blog on the homepage of my website and it keeps displaying the same date, author and title. However the content updates and changes correctly.
Could somebody tell me what i’m doing wrong and why it’s not selecting the right date, title and author but it’s selecting right content?
My current code:
Ajax
$(document).ready(function()
{
GetLatestBlogPost();
});
function GetLatestBlogPost()
{
$.ajax(
{
url: "IsosecWeb/php/getLatestBlogPost.php",
type: 'POST',
dataType: 'json',
beforeSend: function()
{
console.log("Before send...");
},
success: function (successData)
{
console.log(successData);
console.log("successful send...");
}
});
}
PHP
require('../../blog/wp-blog-header.php');
header('Content-Type: application/json');
// Create an object to store the data to be returned in
$newPostArray = array();
$postCounter = 0;
function GetLastestBlogPosts()
{
$args = array( 'numberposts' => 3, 'offset' => 0, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
$postslist = get_posts( $args );
foreach ($postslist as $post)
{
setup_postdata($post);
$postCounter++;
$newPostArray['getLastestBlogDate' . $postCounter] = get_the_date();
$newPostArray['getLastestBlogTitle' . $postCounter] = get_the_title();
$newPostArray['getLastestBlogContent' . $postCounter] = wp_trim_words(preg_replace("/< *[img][^>]*[.]*>/i","", get_the_content(), 80), 80);
$newPostArray['getLastestBlogAuthor' . $postCounter] = get_the_author_link();
}
return $newPostArray;
}
echo json_encode(GetLastestBlogPosts());
Output in console.log
There is a global $post variable exist before your foreach circle, so you should specify the parameter of get_the_date and etc.,like below:
or you can use new wp_query instead of get_posts(),it build a new query loop, and then the get_the_date() and etc. functions are used in a true query loop.