如何用Timber返回仅含标题与Permalink的最新10篇文章列表?
嘿,在Timber里实现这个需求的最优方式,其实是结合WordPress高效查询和Timber的模板分离特性来做,既保证性能又符合Timber的MVC设计思路,分两步来:
第一步:在PHP控制器中获取精简的文章数据
首先要在你的控制器文件(比如page.php或者自定义的模板控制器)里,只查询我们需要的字段——标题和永久链接,避免拉取多余的文章内容(比如正文、摘要这些没用的),这样能大幅提升数据库查询效率。
推荐用下面的写法:
// 初始化Timber上下文 $context = Timber::context(); // 设置查询参数:只取最新10篇已发布文章的ID $post_args = [ 'posts_per_page' => 10, 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC', 'fields' => 'ids' // 先只获取ID,减少单次查询的数据量 ]; // 获取文章ID数组 $latest_post_ids = get_posts($post_args); // 用Timber加载这些文章,仅指定需要的字段 $context['latest_posts'] = Timber::get_posts([ 'post__in' => $latest_post_ids, 'orderby' => 'post__in', // 保持原有的时间排序 'fields' => ['ID', 'post_title', 'guid'] // 明确只取标题和永久链接相关字段 ]); // 渲染对应的Twig模板 Timber::render('components/latest-posts.twig', $context);
为什么要分两次查询?因为先取ID再加载文章,能更精准地控制返回的字段,比直接一次性查询所有字段要高效得多——毕竟我们只需要标题和链接,没必要把文章正文、自定义字段这些都拉出来。
第二步:在Twig模板中渲染列表
接下来在你的Twig模板文件(比如components/latest-posts.twig)里,直接循环渲染即可,Timber已经把文章的属性封装好了,不用手动调用WordPress原生函数:
<div class="latest-posts"> <h3>最新文章</h3> <ul> {% for post in latest_posts %} <li> <a href="{{ post.permalink }}">{{ post.title }}</a> </li> {% endfor %} </ul> </div>
这里post.permalink和post.title都是Timber Post对象的内置属性,直接用就行,非常省心。
如果你需要在全站多个地方复用这个列表,也可以把获取文章的逻辑封装成一个函数,或者通过Timber::add_to_context把latest_posts添加到全局上下文里,这样所有模板都能直接调用。
内容的提问来源于stack exchange,提问作者bigmike7801
相关产品推荐
相关产品推荐

