使用以下解决方案解决:
使用 Home Controller 获取帖子:
public function blog_posts(){
$posts_per_page = 4;
$query_args = [
'post_type' => 'post',
'post_status' => 'publish',
];
$blog = get_posts($query_args);
return $blog;
}
1.1。或使用以下代码获取帖子:
$blog_posts = collect(get_posts([
'post_type' => 'post',
'posts_per_page' => 10,
]))->map(function ($post) {
return (object) [
'categories' => get_the_category($post),
'title' => get_the_title($post),
'url' => get_permalink($post),
'date' => get_the_date('M d, Y', $post),
'excerpt' => substr_replace(get_the_excerpt($post), "", -16),
'image' => get_the_post_thumbnail_url($post)
];
});
从主页模板调用它:
{{ print_r($blog_posts) }}
示例(呈现 4 列博客文章):
{{-- Blogposts Loop --}}
@foreach ($blog_posts as $key=>$post)
@if ($key < 4)
<div class="grid__item medium--one-half large--three-twelfths">
<div class="blog-item">
@if($post->image)
<a href="{{ $post->url }}">
<div class="blog-item__image" style="background-image: url({{ $post->image }})" title="{{ $post->title }}"></div>
</a>
@else
<a href="{{ $post->url }}">
<div class="blog-item__image" style="background-color: #eee" title="{{ $post->title }}"></div>
</a>
@endif
<p class="blog-item__meta">
{{ $post->date }} /
@foreach ($post->categories as $category)
<a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>">
{{ $category->name.' ' }}
</a>
@endforeach
</p>
<h4 class="blog-item__title"><a href="{{ $post->url }}">{{ $post->title }}</a></h4>
<div class="blog-item__excerpt">
@php echo $post->excerpt @endphp <a class="blog-item__excerpt-link" href="{{ $post->url }}">Read More...</a>
</div>
</div>
</div>
@endif
@endforeach