How can you make a ACF be part of a Taxonomy field and part of the WP term object?

So I made ACF called section_image which is an image URL. This ACF is shown on a custom post type taxonomy called Section. All I am trying to do is to get that “section_image” be part of the WP_Term object or maybe find a way to be able to call the image on that specific term i am looping.

Here is the View File

@extends('layouts.app')
@section('content')

<h1 class="display-4 mt-5 text-center advcolor">Knowledge Base </h1>
<div class="container">
  <div class="row">
@foreach ($terms as $term)

      <div class="col-md-3 text-center advcolor">
        <img src="{{$term -> section_image}}" alt="">

        <h2><a href="{{$term -> url}}">{{$term ->name}} </a></h2>
        <p>{{$term -> description}}</p>
      </div>
     @endforeach
  </div>
</div>

@endsection

This is the Controller part

    function terms()
{
    $args = array(
        'orderby'=> 'count',
        'number' => '5',
        'order' => 'DESC'
    );

    $terms = get_terms('section',  $args);

    return $terms;

}

What would be the best way to call that image on the taxonomy I am looping through?

The documentation for get_field() explains how to get fields from taxonomy terms. You could either call that in your template, or augment the array your controller returns:

function terms()
{
  return array_map(function($term) {
      $term->section_image = get_field('section_image', $term);
      return $term;
    }, get_terms([
      'taxonomy' => 'section',
      'orderby'=> 'count',
      'number' => '5',
      'order' => 'DESC'
  ]);
}

I don’t understand how that worked but it worked. I guess to dig a little deeper on how array map works.

Thank you so much!

array_map is (quasi-) functional foreach. The first parameter is a callable of some kind (I used an anonymous function here because it allows me to do the whole thing in one “line”), which will receive the value of each row of the array. Whatever that callable returns will be inserted in place of the original row. The second argument is the array.

The following invocations will return the same result:

$array = [ 'a' => 'hello', 'b' => 'world'];

$foreach = []
foreach ($array as $key => $value) {
  $foreach[$key] = strtoupper($value);
}

$map = array_map('strtoupper', $array);

/**
 * Both $map and $foreach will contain:
 * [ 'a' => 'HELLO', 'b' => 'WORLD' ]
 */

array_map is particularly useful when you want to transform an array in some way.

1 Like

Ok, that totally makes sense. Thank you so much for taking the time to explain you are awesome.

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.