修订版V3
第一件事,第一:你看到inherit
是因为该职位已 被修改或添加附件。所以你应该选择 的帖子,其中publish
的状态。
MySQL查询得到3最新帖子是:
SELECT
posts.ID AS post_id,
posts.post_title,
posts.post_date
FROM
whrg_posts AS posts
WHERE
posts.post_status = 'publish'
AND posts.post_type = 'post'
ORDER BY
posts.post_date DESC
LIMIT 3;
假设你已经建立了邮政和Postmeta模型就像是在
this tutorial提及。我们必须先得到所有的帖子,然后我们必须得到附件
src
链接到该帖子。
添加此功能在您的博客帖子型号
Public function getPostById($post_id)
{
return BlogPost::where('ID', $post_id)
->first();
}
替换此getPosts()
方法在博文型号
Public function getPosts()
{
return BlogPost::with('postmetas')
->status()
->type()
->orderBy('post_date', 'DESC')
->limit(3)
->get();
}
而在你的控制器,你可以像
public function anyPostList()
{
$postImages = []; //array to hold the featured image URL in a key value pair
$BlogPost = new BlogPost();
$posts = $BlogPost->getPosts();
foreach ($posts as $post)
{
if (!empty($post->postmetas))
{
foreach ($post->postmetas as $postmeta)
{
//if _thumbnail_id exists then get its guid for src
if ($postmeta->meta_key == '_thumbnail_id' && !empty($postmeta->meta_value)){
$thumbnail_id = $postmeta->meta_value;
$attachment = $BlogPost->getPostById($thumbnail_id);
if(!empty($attachment->guid))
$postImages[$post->ID] = $attachment->guid;
}
}
}
}
$data = [
'posts' => $posts,
'postImages' => $postImages
];
return view('test.post', $data);
}
要显示访问刀片中的帖子:project_name/reso urces /视图/测试/ post.blade.php
@foreach($posts as $post)
<h1>{{ $post->post_title }}</h1>
<span>Published on : {{ $post->post_date }}</span>
@if(isset($postImages[$post->ID]))
<img src="{{$postImages[$post->ID]}}" width="200"/>
@endif
<div>
{{ $post->post_content }}
</div>
@endforeach
希望它能帮助!
参考:Accessing WordPress Post through Laravel
为什么不使用REST API请求的3个帖子? (wpdomain/wp-json/wp/v2/posts) –
是否所有的文章都有精选图片? –