Support

Account

Home Forums ACF PRO Display Featured Image from Post Object

Solved

Display Featured Image from Post Object

  • I’m needing to display the featured image from a Post Object field. My code is below, which I thought was working until I realized it’s actually displaying the featured image for the Page instead of the post object (which is a Post). What do I need to update below to get the correct image to show?

    
    <?php
              $featured_post = get_field('primary_review');
              if( $featured_post ): 
                $permalink = get_permalink( $featured_post->ID );
                $title = get_the_title( $featured_post->ID );
                $publishDate = get_the_time('F d, Y', $featured_post->ID);
                $categories = get_the_category($featured_post->ID);
              ?>
              <div class="wrapper">
                <a href="<?php echo esc_url( $permalink ); ?>"><?php echo esc_html( $title ); ?></a>
                <?php echo esc_html( $publishDate ); ?>            
                <?php foreach( $categories as $category ) { echo $category->name; } ?>
              </div>
                    <?php
                    $img_id = get_post_thumbnail_id();
                    $size = 'large';
                    $img_src = wp_get_attachment_image_url( $img_id, $size );
                    $img_srcset = wp_get_attachment_image_srcset( $img_id, $size );
                    $title = get_post($img_id)->post_title;
                    $alt = isset(get_post_meta($img_id, '_wp_attachment_image_alt')[0]) ? get_post_meta($img_id, '_wp_attachment_image_alt')[0] : $title;
                    ?>
                    <img src="<?php echo esc_url( $img_src ); ?>"
                    srcset="<?php echo esc_attr( $img_srcset ); ?>"
                    sizes="
                          (min-width: 1170px) 1200px,
                          (min-width: 962px) 992px,
                          (min-width: 738px) 768px,
                          (min-width: 546px) 576px,
                          100vw
                          "
                    alt="<?php echo $alt; ?>"
                    class="">
              <?php endif; ?>
    

    Many thanks in advance!

  • You just need to supply the post ID here

    
    get_post_thumbnail_id($featured_post->ID);
    
  • Perfect, many thanks!

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.