get_field in default WordPress
When you run get_field
, the function will try to guess the object where it should look for the custom field from the context. The context is normally The Loop.
So, if you run $cover_image_id = get_field( 'city_hero_image' );
, ACF will try get the custom field city_hero_image
from the current post’s ID, which it can’t find. There’s also no city_hero_image
defined on a post, it’s defined on your term.
- If you run
get_field
inside the loop, it will take the current post’s ID to load a field. But, with Timber you’re never inside The Loop. Timber is in fact used to get rid of The Loop.
- If you want to load a field from a term object (in your case
city_hero_image
), you’d need to explicitly tell get_field
to look in that taxonomy with get_field( 'city_hero_image', 'city_termid' )
, while termid will be the id of the term you want the data for.
get_field in Timber
In Timber, get_field
works a little different. Timber will populate the post or term object with the custom fields as properties.
If you have a custom field city_hero_image
in your taxonomy, you can access it in multiple ways:
in PHP
- Directly via its property:
$category->city_hero_image
- Through the
get_field
method of a Timber\Term object:
$category->get_field('city_hero_image)
in Twig
- Directly via its property:
{{ category.city_hero_image }}
- Through the
gef_field
method:
{{ category.get_field('city_hero_image') }}
The same works for ACF fields on Timber\Post objects. You only need to call get_field
explicitly when you want to access data of field types Repeater or Flexible Content.
Putting it together
Let’s look at this in your example. You first need to get the term that is displayed. For archive pages, you can use the function get_queried_object()
, which will return an object depending on the archive that is accessed:
- For term archives, it will be a
WP_Term
object.
- For post type archives, it will be a
WP_Post_Type
object.
- For author archives, it will be a
WP_User
object.
- and so on...
You have a term archive (taxonomy-city.php
), so it would be
$term = new \Timber\Term( get_queried_object() );
$cover_image = $term->city_hero_image;
$context['term'] = $term;
$context['cover_image'] = new \Timber\Image($cover_image);