【问题标题】:In Timber pass an ID in the loop to a WP function在 Timber 中,将循环中的 ID 传递给 WP 函数
【发布时间】:2019-02-20 15:40:13
【问题描述】:

在 Timber/Twig 中,我使用以下方法显示事件列表:

页面事件.php:

$context = Timber::get_context();

$events = array(
    'post_type' => 'event',
    'posts_per_page' => 10,
);

$context['events'] = Timber::get_posts( $events );

Timber::render( array( 'page-' . $post->post_name . '.twig', 'page-home.twig' ), $context );

page-events.twig

{% for event in events %}
    <li>{{ event.name }} - *country* </li>
  {% endfor %}

我还想显示与该活动相关的国家/地区。这被存储为一个术语。在 WordPress 中,我通常会使用:

$country = get_the_terms( get_the_ID(), 'country');
echo $country[0]->name;

如何使用 Timber 将 ID 传递给 get_the_terms($id, 'country')

我搜索了 Timber 文档并用 Google 搜索,但找不到答案。

我试过{{ get_the_term( event.id, 'country' ) }}{% get_the_term( event.id, 'country' ) %} 和类似的,但没有成功。

【问题讨论】:

    标签: php wordpress twig timber


    【解决方案1】:

    如果要在 Twig 中使用 PHP 函数,则需要使用 function()fn(),如 Functions Guide 中所述。

    对你来说,这意味着在 Twig 中,你可以使用 {{ get_the_term( event.id, 'country' ) }} 而不是

    {{ fn( 'get_the_terms', event.id, 'country' ) }}
    

    您通过event.id 传递ID 是正确的。但是,该函数返回一个数组,您不能这样显示。您需要将其转换为字符串或对其进行循环。以下是使用 Twig 的 first 过滤器仅显示该数组中的第一个国家/地区的方法:

    {{ fn( 'get_the_terms', event.id, 'country' )|first }}
    

    如果您有多个国家/地区,您可以使用join 将它们转换为逗号分隔的列表:

    {{ fn( 'get_the_terms', event.id, 'country' )|join(', ') }}
    

    还有一件事我们可以优化。除了使用get_the_terms(),我们可以使用可用于Timber\Post 对象的terms() 方法:

    {% for event in events %}
        <li>{{ event.name }} - {{ event.terms('country')|first }}</li>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-18
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2021-03-13
      • 2017-10-30
      相关资源
      最近更新 更多