【问题标题】:WordPress the_date() doesn't work with TimberWordPress the_date() 不适用于 Timber
【发布时间】:2020-09-19 10:21:08
【问题描述】:

我一直在使用 Timber 来获取帖子列表。它工作正常,但我需要像这样“按日期排序”:

= 1 月 2 日 = 发布 5 帖子 4 = 1 月 1 日 = 帖子 3 帖子 2 位置 1

WordPress 函数 the_date() 可以做到这一点,但我无法使用 Timber 获得相同的结果。 the_date 返回 null

索引.php

$context            = Timber::context();
// $context['posts']    = new Timber\PostQuery();
$context['posts']   = Timber::get_posts(); // both doesn't work

$templates = array( 'archive.twig', 'index.twig' );

Timber::render( $templates, $context );

存档.twig

<div class="s-archive__posts-list">
    {% for post in posts %}

        {{ the_date() }} // function registered via $twig->addFunction( new Timber\Twig_Function( 'the_date', 'the_date' ) );
        {{ fn('the_date') }} - doesn't work too. I was guessing, maybe, fourth param of this function the case (echo) but it's not {{ fn('the_date', 'M, Y', '', '', false ) }}. 

        {% include 'content/content-archive.twig' %}

    {% endfor %}
</div><!-- /s-archive__posts-list -->

我必须做些什么才能使其按预期工作?

更新 它适用于

$context['posts'] = Timber::query_posts();

【问题讨论】:

    标签: timber


    【解决方案1】:

    问题表明对 Wordpress 函数 the_date() 的调用返回 null。

    这是因为_date函数只会在没有其他参数的情况下回显日期并且不会返回值。对 the_date 的完整调用具有这种形式

    the_date(string $format = '', string $before = '', string $after = '', bool $echo = true)

    echo 的默认值为 true - 如果您希望它返回一个值,那么您需要将此参数设置为 false。见https://developer.wordpress.org/reference/functions/the_date/

    完整的描述。

    Wordpress 还提供了一个 get_the_date 函数,它不回显但总是返回一个日期,请参阅https://developer.wordpress.org/reference/functions/get_the_date/

    我不熟悉 Timber,所以不知道什么最适合您想要实现的目标。

    【讨论】:

    • 我尝试将 echo 设置为 false (在我的问题中提到过)但它没有用。
    • 您能否展示您用于在 the_date 调用中设置 echo false 的代码 - Timber 是否传递此类参数?
    • {{ fn('the_date', 'M, Y', '', '', false ) }} 应该是,第一个参数是函数名,其他参数是它的参数在WordPress中
    • 你能在浏览器上使用开发工具吗?看看在
      之后立即生成的实际代码 - 我假设你刚刚得到了 {{ fn ('the_date', 'M, Y', '', '', false ) }} 那里而不是对先前注册的 the_date 的调用?你的参数看起来不错。如果它不起作用,您可以尝试 {{fn('get_the_date')}} 代替,不传递任何参数,只是为了查看日期是否实际上是由 Timber 放入的?
    • 我通过将木材上下文替换为 query_posts 来解决它。不确定这是不是一个好主意,但至少它奏效了。感谢您的帮助!
    【解决方案2】:

    如果您使用像the_date() 这样的函数,该函数将依赖于设置为全局变量的$post。但是,在 Timber 中,我们不依赖 $post 全局变量,因为它通常更难控制。

    相反,我们使用post 本身的属性和方法。对于帖子的日期,您可以使用{{ post.date }}

    {% for post in posts %}
        {{ post.date }}
    
        {% include 'content/content-archive.twig' %}
    {% endfor %}
    

    这样,您也不必向$twig-&gt;addFunction() 注册函数。

    【讨论】:

    • 感谢您的回复!问题是我不需要每个帖子的日期,只需要一组具有相同日期的帖子。我可以通过使用 query_posts 或像这样的 twig-way-condition 来解决这个问题 ``` {% if posts[loop.index0].date is not same as posts[loop.index0 - 1].date %} { { post.date }} {% endif %} ``
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签