wordpress-theming - 我应该在单个 wordpress 模板中使用 $post = Timber::query_post() 还是 $post = new TimberPost() ?

标签 wordpress-theming timber

我在官方 Timber 存储库上读到,有关使用的一般问题应在此处发布。

我是 Timber/Twig 的新手,我有一个非常“基本”的问题。

在入门主题中,我看到在 single.php 中设置了传递给 $context 的 $post 变量

$post = Timber::query_post()

page.php 是用

设置的
$post = new TimberPost();

那么,当我需要设置一个 single-cpt.php 时,我应该使用什么方法呢? Timber::query_post() 还是 new TimberPost()

我已经尝试了这两种方法并且它们都有效,但是正确的方法是什么?

谢谢!

PS:我已经看到在 index.php 中,$context['post'] 正在使用 new Timber\PostQuery() 进行设置。这是否基本上重现了模板层次结构的标准循环?

最佳答案

我知道对于使用哪些方法可能会有一些混淆。目前,有很多方法可以做到这一点,您尝试过的所有方法都应该有效。

在即将推出的 Timber 版本 2 中,我们试图统一这一点,我们将弃用一些仍然存在的方法。因此,从现在开始,您应该按照以下方式进行操作。


2020 年 3 月更新 – 我们反复讨论了 2.x 的新 API 应该如何,我们已经提出了一个几乎固定的解决方案。有些东西会在那里改变,你可以看看这个 pull request如果你想了解更多。

在那之前,这是我们推荐的做事方式:


获取单个帖子

<罢工>

<罢工>
$post = new Timber\Post();

<罢工>

$post = Timber::get_post();

获取帖子集合

<罢工>

<罢工>
$post = new Timber\PostQuery();

<罢工>

$post = Timber::get_posts();

如果您想在帖子中使用分页,您仍然需要使用Timber\PostQuery。 :

$post = new Timber\PostQuery();

(在 Timber 2.x 中 Timber::get_posts() 可以使用分页,但在 1.x 中还不行。)

标准循环

I've seen that in the index.php the $context['post'] is being setup with new Timber\PostQuery(). Does this basically reproduce the standard loop of the template hierarchy?

是的!

事实上,如果你不传递任何参数给PostQuery() , 你甚至不必设置 $context['posts'] , 因为木材 does that already for you in Timber::get_context() .

index.php

<?php
use Timber\Timber;

$context = Timber::get_context();

Timber::render( 'index.twig', $context );

使用命名空间类名

目前,您可能仍会看到 TimberPost()而不是 Timber\Post() .对于版本 1,所有 Timber 类都是命名空间的,因此从现在开始推荐的方法是在 PHP 中使用命名空间的类名,例如Timber\Term而不是 TimberTerm .

但是!在 Twig 中,您仍然会使用非命名空间版本:

{% set post = Post(post_id) %}

{% set post = TimberPost(post_id) %}

我希望这能解决问题。

关于wordpress-theming - 我应该在单个 wordpress 模板中使用 $post = Timber::query_post() 还是 $post = new TimberPost() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737508/

相关文章:

css - WordPress 主题响应使用@media 不工作

WordPress简码参数

php - 如何在WordPress发布循环中正确定位嵌入式Google广告

php - 如何在类别页面以及该页面的所有子类别和帖子上的正文中添加自定义类名?

php - 如何在自定义 wordpress 主题上添加 Logo

wordpress - Post Object Timber/Twig WordPress 问题

php - 在木 Twig 文件内循环

wordpress - 无法在模块外部使用 import 语句 - Timber Starter 主题 - Gulp

php - Timber(Twig)如何调用wordpress函数

wordpress - 将第二个自定义菜单添加到全局上下文时出现问题