I'm using the following shortcode which pulls from an ACF post object field and works to display post titles as links in a list:
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' );
How can I add the post featured image to the link element so both the title and the image display, and both link to the post? I've tried the following and variations but I must be getting my syntax wrong as I either get an empty image element or nothing at all.
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' );
You might try using
get_the_post_thumbnail($option->ID, "full")
instead. This will give you the full image with source set, etc.
it might look something like this:
$html .= '<li><a href="' . esc_url( $permalink ) . '"><h3>' . esc_html( $title ) . '</h3>' . $featured . '</a></li>';
Maybe view the actual HTML that gets output (inspector or view-source) and you will be able to see why your image was empty.
lastly, (if you haven't already) use var_dump($featured); so you can see exactly what is being returned.