php - 如何在 Sage 中创建带有博客文章的静态首页?
问题描述
我正在尝试创建一个静态主页自定义模板,其结构如下:
- 英雄
- 一些图片和文字
- [博客文章]
- 页脚
问题是我的代码显示帖子类型为:页面,而不是帖子类型:帖子。
我使用 Sage (Roots.io)(Blade 模板引擎),创建了一个名为template-home.blade.php的模板。我已经尝试从content.blade.php复制代码,并在我的template-home.blade.php上使用它。
这是我用来获取博客文章的content.blade.php中的代码:
<article @php post_class() @endphp>
<header>
<h2 class="entry-title"><a href="{{ get_permalink() }}">{!! get_the_title() !!}</a></h2>
@include('partials/entry-meta')
</header>
<div class="entry-summary">
@php the_excerpt() @endphp
</div>
</article>
预期结果:它应该显示所有帖子类型为post 的帖子。像“博客文章标题 1”、“博客文章标题 2”等。
当前结果:复制的代码显示帖子类型为:page的帖子。比如“家”、“关于”等。
请帮忙。谢谢你。
解决方案
使用以下解决方案解决:
使用 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
推荐阅读
- c - C 结构值重置为 NULL
- python - Python 在使用 libhdf5.103.dylib 插件时意外退出
- android - 使用 KeyStore 进行 RSA 解密时出现间歇性 IllegalBlockSizeException
- reactjs - 无法处理从服务器获取的数据
- java - 具有 Azure 服务总线的 Java 应用程序
- c# - 1 == 0 返回真。为什么?
- android - 平板电脑的背景图像大小
- css - SCSS 在从不同文件夹导入时未正确传递相对图像引用
- java - Spring PersistanceContext,EntityManager 并使用您的数据库
- docker - 当 CNI 插件在容器级别工作时,kubernetes pod 如何获取 IP 而不是容器而不是它