Roots Discourse

Adding ACF variable to custom post type

Hi, I’m trying to add a variable, get_field(‘campus_link’) to a custom post type function in my controller file, here’s my code:

public function campusLoop()
    {
        $campus = get_posts([
        'post_type' => 'campus',
        'posts_per_page'=>'-1',
        'order' => 'ASC'
        ]);
        
        return array_map(function ($post) {
            return [
            'content' => apply_filters('the_content', $post->post_content),
            'excerpt' => apply_filters('get_the_excerpt', $post->post_excerpt),
            'thumbnail' => get_the_post_thumbnail($post->ID, 'large'),
            'thumbnail_url' => get_the_post_thumbnail_url($post->ID, 'large'),
            'title' => $post->post_title,
            ];
        }, $campus);
    }

How would I add the ACF field in here and then display the data from that field in a view?

Thanks!

The same way you’re getting the thumbnail.

The same way you’re displaying any of the other variables in that post loop.

Thanks for the quick response!

So in the controller file:
‘link’ => get_field(‘campus_link’),

And to display:
{!! $campus[‘link’] !!}

?

I feel like i’ve tried this exact setup to no avail…it’s possible I’ve been staring at it for too long and had an error in my text somewhere :slight_smile:

Have you read through the documentation for get_field()? https://www.advancedcustomfields.com/resources/get_field/

You probably need to pass the id of the post to get_field() in your loop. Otherwise it’s trying to get that field from whatever is in the $post global.

I did read through the docs for get_field() but still having issue getting data to show. I did figure out a workaround though…using:

‘title’ => $post->post_title as the “href” value for the link.

I’ll have to look into this further when I have more time.

Thanks for all of your help!

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