Your Location is: Home > Timber

WordPress the_date() doesn't work with Timber

From: Yugoslavia View: 1169 Aliakseyenka Ihar 

Question

I've been using Timber to get list of posts. It works fine, but then I needed to "sort by the date" like this:

= Jan, 2nd = Post 5 Post 4 = Jan, 1st = Post 3 Post 2 Pos 1

WordPress function the_date() would do it, but I cannot get same result with Timber. the_date returns 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 -->

What do I have to do to make it work as I expected?

UPDATE It works with

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

Best answer

The question states that a call to the Wordpress function the_date() is returning null.

This is because the_date function will just echo the date if it has no other parameters and will not return a value. The full call to the_date has this form

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

The default value for echo is true - if you want it to return a value instead then you need to set this parameter to false. See https://developer.wordpress.org/reference/functions/the_date/

for a full description.

Wordpress also provides a get_the_date function which doesn't echo but always returns a date see https://developer.wordpress.org/reference/functions/get_the_date/

I am not familiar with Timber so do not know what is best for exactly what you are trying to achieve.