I have a custom field called category_image which is an image field for categories.
I have another custom field called categories_to_show which is a taxonomy for the homepage to select which categories to show.
The categories_to_show is working fine, but I'm struggling to get category_image. If I print_r it's not in the array.
In my page-home.php file:
$context['categories_to_show'] = get_field('categories_to_show') ?? '';
In my page-home.twig file:
{% for c in categories_to_show %}
{{c.name}}
{{c.category_image}}
{% endfor %}
c.name works, c.category_image does not. But not suprising as it's not in the categories_to_show array:
Array ( [0] => WP_Term Object ( [term_id] => 4 [name] => Technology [slug] => technology [term_group] => 0 [term_taxonomy_id] => 4 [taxonomy] => category [description] => [parent] => 0 [count] => 1 [filter] => raw ) [1] => WP_Term Object ( [term_id] => 1 [name] => Uncategorized [slug] => uncategorized [term_group] => 0 [term_taxonomy_id] => 1 [taxonomy] => category [description] => [parent] => 0 [count] => 1 [filter] => raw ) )
Could anyone point me in the right direction?
It looks like your problem is that you have a WP_Term
object, but you’ll want to have a Timber\Term
object so that you can access the meta data more easily.
In PHP, you can use Timber::get_terms()
to convert an array of term IDs or WP_Term
objects into Timber\Term
objects.
PHP
$context['categories_to_show'] = get_field('categories_to_show')
? Timber::get_terms( get_field('categories_to_show') )
: [];
Then, if you loop through your categories, you can access all methods that are available for Timber\Term
.
You can use c.category_image
to access the category_image
meta value, but I’d use the meta()
function for a more future-proof way.
Twig
{% for c in categories_to_show %}
{{ c.name }}
{{ c.meta('category_image') }}
{% endfor %}
Depending on what the meta value for your image contains, you might also have to convert it to a Timber\Image
object first before you can work with it.
{# Full #}
{{ Image(c.meta('category_image')).src }}
{# Large size #}
{{ Image(c.meta('category_image')).src('large') }}
Pro tip – you might save some performance if you choose to return only the image ID for your image field instead of an image array in your ACF field settings.
Of course, if you prefer to work with the image array that ACF returns, that’s fine as well.