I am using twig templates with wordpress and I am trying to output a date but when I try to format the date it formats correctly but it renders today’s date, not the date that I am trying to render.
{% for item in program_schedule %}
{{ item.training_date_current }} // renders correctly 05/Aug/2021
{{ post.published_at|date("d/M/Y") }} // renders 07/Jul/2021 - should be same as above
{% endfor %}
It is very strange, any idea why this is happening and how to fix?
Thank you.
2
Answers
In php the date method has 2 arguments from which 1 is optional as mention in manual. The string format is required and the second argument being timestamp. If the timestamp is not provided then it takes the current timestamp and gives you today’s date (07/Aug/2021). It could be that you expected
post.published_at|date("d/M/Y")
to pass the published_at as second argument which wasn’t the case.You would want to call date method as
date("d/M/Y", $dt)
where $dt is the timestamp. One way of create timestamp is by usingmktime(hour, minute, second, month, day, year)
Because in a loop you set your singular post as
item
but applyingpublished_at
atpost
which in Timber may served from global context (basically it is current singular page). You may install Debug Timber Bar it will help you to find what in the context or check{{ dump(_context) }}
. Change your loop to