修訂版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) –
是否所有的文章都有精選圖片? –