微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WordPress the_date不适用于Timber

如何解决WordPress the_date不适用于Timber

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

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

wordpress函数the_date()可以做到,但是Timber无法获得相同的结果。 the_date返回null

Index.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 );

Archive.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'] =木材:: query_posts();

解决方法

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

这是因为,如果没有其他参数,the_date函数将仅回显日期,并且不会返回值。完整的the_date调用具有以下格式

the_date(字符串$ format ='',字符串$ before =``,字符串$ 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不熟悉,所以不知道什么对您要实现的目标最合适。

,

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

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

{% for post in posts %}
    {{ post.date }}

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

这样,您也不必使用 $twig->addFunction() 注册函数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。