如何使WPQuery自定义POST类型在Twig/Timber中工作

时间:2020-10-07 作者:David

我对树枝和木材完全陌生。我读了他们的文档,看了一些教程,但我无法让它工作。

我有一个带有自定义职位类型和ACF字段的WP查询:

    <?php
          $args = array( \'post_type\' => \'what_our_clients_say\', \'posts_per_page\' => 2 );
          $loop = new WP_Query( $args );
          while ( $loop->have_posts() ) : $loop->the_post();
              echo \'<div class="what-our-client-say-single-wrapper p-relative aos-init aos-animate" data-aos="fade-up" data-aos-delay="100">\';
              echo \'<div class="what-our-client-say-single-wrapper-violet"></div>\';
                echo \'<div class="what-our-client-say-inner-wrapper p-relative">\';
                echo \'<div class="what-our-client-say-inner-wrapper-img"><img src="\' . get_field(\'what_our_clients_img\') . \'" class="img-client img-fluid"></div>\';
                echo \'<div class="what-our-client-say-inner-wrapper-all-txt"><div  class="what-our-client-say-inner-wrapper-header"><h3>\'.get_the_title().\'</h3></div>\';
                echo \'<div class="what-our-client-say-inner-wrapper-txt"><p>\'.  get_the_excerpt() .\'</p></div><div class="what-our-client-say-inner-wrapper-who"><p>\'. get_field("what_our_clients_say_who") .\'</p></div>\';
                echo \'</div></div><a href="https://pragmaticbrains.com/case-study" target="_blank" class="button big primary-colorbg no-hover what-our-client-say-special-btn">READ MORE\';
                echo \'</a>\';
              echo \'</div>\';
          endwhile;
          wp_reset_postdata(); 
      ?>
当我把它传递到php文件时,它就工作了。然而,当我尝试让它在中工作时。我的主要问题不是字段或摘录/标题部分(我将其转换为:{{post.title}}}),而是这个循环:

 $args = array( \'post_type\' => \'what_our_clients_say\', \'posts_per_page\' => 2 );
          $loop = new WP_Query( $args );
          while ( $loop->have_posts() ) : $loop->the_post();
(...)
   endwhile;
          wp_reset_postdata(); 

零件。我将非常感谢你的帮助

1 个回复
最合适的回答,由SO网友:Jared 整理而成

我认为这就像使用木材一样简单Timber::get_posts() 而不是WP_Query 类别:

$context[\'testimonials\'] = Timber::get_posts( [\'post_type\' => \'what_our_clients_say\', \'posts_per_page\' => 2] );
Timber::render(\'whatever.twig, $context);
。。。从那里,您可以循环浏览推荐信,并通过meta访问ACF值:

{% for post in testimonials %}
    <h1>{{ post.attribution }} says:</h1>
    {# more here #}
{% endfor %}

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post