I am having a hard time getting the WordPress thumbnail to show up when I am using Advanced Custom Fields Pro Post Object.
My goal is to have the user select a single featured post to show up after the 6th post on the blog page.
This is my code (which is pretty much directly from ACF documentation):
<?php $featured_post = get_field('featured_post', 'option'); if( $featured_post ): ?> <?php echo esc_html( $featured_post->post_title ); ?></h3> <?php the_post_thumbnail(); ?> <?php endif; ?>
This returns the correct title but the wrong featured image (from the post above).
The code above is called inside the loop on index.php inside the featured template part.
$counter = 1; /* Start the Loop */ while ( have_posts() ) : the_post(); /* * Include the Post-Type-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Type name) and that will be used instead. */ get_template_part( 'template-parts/content', 'get_post_type()' ); //check the counter and display your content if( $counter === 3 && !is_paged() ) { ?> <?php get_template_part('template-parts/components/component', 'subscribe'); ?> <?php } elseif ( $counter === 6 && !is_paged() ) { ?> <?php get_template_part('template-parts/components/component', 'featured'); ?> <?php } //update the counter on every loop $counter++; endwhile;
I have tried the other code examples on the documentation page but those return all of my posts (again with only one thumbnail, not the correct thumbnail per post).
I am not sure where to go from here.
Anyone who can help would be greatly appreciated!
Advertisement
Answer
Since this is not in the loop context, the function does not find the correct post object set up to take the ID from. Use get_the_post_thumbnail
instead, that takes the post id as parameter.
<?php echo get_the_post_thumbnail( $featured_post->ID ); ?>