如何在这个短代码中显示从ACF字段中提取的特色图像?



我正在使用以下短代码,它从ACF post对象字段中提取,并用于在列表中显示作为链接的帖子标题:

function related_for_products( $atts ) {
global $post;
$related = get_field('product_related');
$html = '';
if( $related ) {
$html .= '<ul>';
foreach( $related as $option ) {
$permalink = get_permalink( $option->ID );
$title = get_the_title( $option->ID );
$html .= '<li><a href="'. esc_url( $permalink ) . '">' . esc_html( $title ) . '</a></li>';
}
$html .= '</ul>';
}
return $html;
}
add_shortcode( 'related', 'related_for_products' );

如何将文章特色图像添加到link元素中,以便标题和图像都显示,并且都链接到文章?我已经尝试了以下和变化,但我必须得到我的语法错误,因为我要么得到一个空的图像元素或什么都没有。

function related_for_products( $atts ) {
global $post;
$related = get_field('product_related');
$html = '';
if( $related ) {
$html .= '<ul>';
foreach( $related as $option ) {
$permalink = get_permalink( $option->ID );
$title = get_the_title( $option->ID );
$featured = get_the_post_thumbnail_url( $option->ID );
$html .= '<li><a href="'. esc_url( $permalink ) . '">' . esc_html( $title ) . ' <img src="'. esc_url( $featured ) . '"></a></li>';
}
$html .= '</ul>';
}
return $html;
}
add_shortcode( 'related', 'related_for_products' );

您可以尝试使用

get_the_post_thumbnail($option->ID, "full")

。这将为您提供带有源集的完整图像,等等。

它可能看起来像这样:

$html .= '<li><a href="' . esc_url( $permalink ) . '"><h3>' . esc_html( $title ) . '</h3>' . $featured  . '</a></li>';

也许查看实际的HTML输出(检查器或视图源),你将能够看到为什么你的图像是空的。

最后,(如果还没有)使用var_dump($featured);因此,您可以确切地看到返回的是什么。

最新更新