ACF taxonomy field in controller

I’m currently trying to setup ACF taxonomy field value in my controller. Currently its outputting a number instead of the name. I’ve read through a lot of documentation and tried lots of examples relating to terms but keep coming back to the code posted here. I’d rather not post all the things of tried because it’s trashy. Not sure if I should be esc_html or apply a filter for the ACF taxonomy select or querying taxonomy or terms. In the ACF setup, the options are Term Object and Term ID. Term Object returns an error - Object of class WP_Term could not be converted to string and Term ID returns, well an ID.

I’ve tried following:

My ACF taxonomy field in controller:
'joblocation' => get_field('pj_job_location', $post->ID),

My current Controller code:

namespace App\Controllers;
use Sober\Controller\Controller;
class TemplateJobs extends Controller
    protected $acf = true;
    public static function jobsLoop($postType)
        $item = get_posts([
            'post_type' => $postType,
            'posts_per_page' => 50,

        return array_map(function ($post) {
            return [
            'title' => apply_filters('get_the_title', $post->post_title),
            'excerpt' => apply_filters('get_the_excerpt', $post->post_excerpt),
            'postdate' => get_field('pj_job_post_date', $post->ID),
            'jobtype' => get_field('pj_employment_type', $post->ID),
            'permalink' => apply_filters('permalink', get_permalink($post)),
            'joblocation' => get_field('pj_job_location', $post->ID),
        }, $item);

This is simplistic. Within the blade controller post loop:
{!! $item['joblocation'] !!}

This outputs a number. Any guidance/reference would be great. Cheers.

Set up the field to return a Term Object. Then do for example var_dump(get_field('pj_job_location', $post->ID)); die(); before the return-statement in your function. That should output the term object and you can see the data that ACF returns for that field. When you are familiar with the data, delete the dump and die.

Off the top of my head, I think the property that you are looking for is called term_name so you can for example do {{ $item['joblocation']->term_name }}.

This probably has nothing to do with Sage but is more of a ACF-thing.

1 Like

Thanks for taking the time to look at this. This gave me a few ideas and after a few minutes got it to work. :grinning:

  1. ACF Taxonomy as a Term Object
  2. Controller post array: 'joblocation' => get_field('pj_job_location', $post),
  3. Output in post loop {{ $item['joblocation']->name }}

Ah, ”name” is the name of the name property :slight_smile: Seems logical and I will try to remember it from now on. Glad you got it to work. var_dump and its relatives are your best friend when debugging.

1 Like

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