获取Post缩略图显示单个Post对象(WP + ACF)



当我使用Advanced Custom Fields Pro Post Object时,我很难让Wordpress缩略图显示出来。

我的目标是让用户选择一个单一的特色帖子显示在博客页面上的第6个帖子之后。

这是我的代码(几乎直接来自ACF文档):

<?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; ?>

返回正确的标题,但错误的特征图像(来自上面的帖子)。

上面的代码是在index.php的循环中调用的。

$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;

我已经尝试了文档页面上的其他代码示例,但这些示例返回了我所有的帖子(再次只有一个缩略图,而不是每个帖子的正确缩略图)。

我不知道从这里该往哪里走。

任何能帮忙的人都会非常感激!

由于这不在循环上下文中,因此该函数没有找到设置为从中获取ID的正确post对象。使用get_the_post_thumbnail代替,它将post id作为参数。

<?php echo get_the_post_thumbnail( $featured_post->ID ); ?>

最新更新