Home > Software engineering >  How do I get and set Advanced Custom Fields data as a variable in Timber $context to use in a post q
How do I get and set Advanced Custom Fields data as a variable in Timber $context to use in a post q

Time:02-23

I want to get and set the value of an ACF field into a variable in my home.php file and then use this as part of a query.

So, for example, if a user enters the word 'event' in the the field 'cat_name' in the CMS, I wanted to get and set this as a variable and then use this as part of a basic query to return all posts with a category of event..

What I have at the moment is below. How do I access ACF data in home.php / $context and then store it in the $my_var variable. Is this possible?

<?php
    $context = Timber::get_context();
    $context['post'] = new Timberpost();

    $my_var = get_field('cat_name');

    
    $context['posts'] = Timber::get_posts(array(
       'post_type' => 'post',
       'category_name' => $my_var
    ));
    
    Timber::render('home.twig', $context);
?>

CodePudding user response:

You need to get the field value with the TimberPost method get_field() :

$my_var = $context['post']->get_field('field_name');
  • Related