I am currently getting an undefined variable error returned in php using twig/timber declarations on WordPress and even though the code below returns and displays the posts on the page as intended, I am still receiving the error message in debug mode (See below). I realise PHP vars need to be declared and that I am not declaring $jobs anywhere before the loop, but my understanding is that $context converts the post type 'jobs' into a php var. If not what am I doing wrong and how to I declare it?
ERROR MESSAGE:
Notice: Undefined variable: jobs in /Applications/MAMP/htdocs/xxxx.co.uk/wp-content/themes/xxxx/front-page.php on line 19
PHP file:
$context['jobs'] = Timber::get_posts('post_type=jobs&posts_per_page=3');
if(is_array($jobs)){ /* line 19 */
// Closing date display format (e.g. 24th October 2019)
foreach( $jobs as &$job ){
$job->job_close_date_formatted = date( 'jS F Y', strtotime( $job->job_close_date ) );
}
}
$context['options'] = get_fields('acf-theme-options');
TWIG file:
{% for job in jobs %}
{% include 'components/home-job-panel.twig' %}
{% endfor %}
The jobs
are being displayed because u've defined them in $context
$context['jobs'] = Timber::get_posts('post_type=jobs&posts_per_page=3');
The foreach
you are doing now has no impact on any of the jobs as $jobs
is indeed undefined. If you wanted to modify some data you would need to use the following foreach
if (is_array($context['jobs'])) foreach($context['jobs'] as &$job) {
I wouldn't actually bother with transforming data inside your controller. Imho that is the purpose of filters inside twig
/timber
{% for job in jobs %}
{{ job.job_close_date | date('jS F Y') }}
{% endfor %}