How to display custom fields of a custom post type on the homepage

I have a custom post type named “Press” that has a couple custom fields, “Intro” and “Excerpt” which I’m trying to display in my view.

In my App.php controller, I have:

public function pressPostsLoop()
    $press_posts = get_posts([
        'post_type' => 'press',
        'posts_per_page' => '3'
    return array_map(function ($post) {
        $intro = get_field('intro');
        $excerpt = get_field('excerpt');
        $text = strip_shortcodes($post->post_content);
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $text_length = apply_filters('text_length', 60);
        $text_more = apply_filters('text_more', ' ' . '[…]');
        $text = wp_trim_words($text, $text_length, $text_more);

        return [
            'title' => apply_filters('the_title', $post->post_title),
            'link' => get_the_permalink($post->ID),
            'date' => get_the_date( 'l F j, Y' ),
            'intro' => wp_kses_post($intro),
            'excerpt' => $excerpt,
            'text' => $text,

    }, $press_posts);

And in my page.blade.php view, I have:

@foreach($press_posts_loop as $press_post)
  <div class="col-12 col-md-4">
    <p>{!! $press_post['link'] !!}</p>
    <p>{!! $press_post['title'] !!}</p>
    <p>{!! $press_post['date'] !!}</p>
    <p>intro: {!! $press_post['intro'] !!}</p>
    <p>excerpt: {!! $press_post['excerpt'] !!}</p>
    <p>text: {!! $press_post['text'] !!}</p>

Which is displaying the link, title, date, and text for the three posts but not intro or excerpt. Why is that?

I’m also trying to filter those posts to show the three most recent that have a custom toggle field titled “Featured on the Homepage” set to true. How can I do that?

For reference, I’m basing my code on this topic.

outside of a query loop you need to pass the ID to get_field() – so get_field('intro', $post->ID)

1 Like

Thanks @Log1x that worked.

For future reference, the only change I made was updating the relevant line within the array_map function:

return array_map(function ($post) {
  $intro = get_field('intro', $post->ID);
1 Like