我正在尝试在我网站的主页上显示我的WordPress博客中的最新3个帖子,并且它会一直显示相同的日期,作者和标题。但是内容会正确更新和更改。
有人可以告诉我我做错了什么,为什么它没有选择正确的日期,标题和作者,但是它选择了正确的内容?
我目前的代码:
的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());
在console.log中输出
答案 0 :(得分:1)
在foreach圈之前存在一个全局$ post变量,因此您应该指定get_the_date等参数,如下所示:
$newPostArray['getLastestBlogDate' . $postCounter] = get_the_date('Y-m-d H:i:s',$post);
$newPostArray['getLastestBlogTitle' . $postCounter] = get_the_title($post);
$newPostArray['getLastestBlogContent' . $postCounter] = wp_trim_words(preg_replace("/\< *[img][^\>]*[.]*\>/i","", get_post_field('post_content', $post->ID);, 80), 80);
$newPostArray['getLastestBlogAuthor' . $postCounter] = get_author_posts_url(get_post_field('post_author', $post->ID));
或者您可以使用新的wp_query而不是get_posts(),它构建一个新的查询循环,然后在真正的查询循环中使用get_the_date()等函数。