I’m building a related products list on a product detail page by dynamically populating a select field with custom post type product titles like this, which is working as intended:
function my_acf_load_field( $field ) {
// Reset choices
$field['choices'] = array();
// Query products
$args = array(
'numberposts' => -1,
'post_type' => 'products'
);
$the_query = new WP_Query( $args );
if ($the_query->have_posts()) {
while( $the_query->have_posts() ){
$the_query->the_post();
$value = get_post_field( 'post_name', get_the_ID() );
$label = get_the_title();
// Append to choices
$field['choices'][ $value ] = $label;
}
wp_reset_postdata();
}
return $field;
}
add_filter('acf/load_field/name=related_products', 'my_acf_load_field');
On the product detail page, I’m looping through the selected fields like this, which is also working as intended:
<?php
$relatedproducts = get_field('related_products');
if( $relatedproducts ): ?>
<ul>
<?php foreach( $relatedproducts as $relatedproduct ): ?>
<li><?php echo $relatedproduct; ?></li>
<?php endforeach; ?>
</ul>
<?php
endif;
?>
The issue: I would like to access the titles, permalinks, excerpts and thumbnails of the selected related products, but I’m not sure how to access that information from the foreach. I tried doing this:
<?php
$relatedproducts = get_field('related_products');
if( $relatedproducts ): ?>
<ul>
<?php foreach( $relatedproducts as $relatedproduct ):
setup_postdata($relatedproduct);
?>
<li><?php echo the_title(); ?></li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); ?>
<?php
endif;
?>
But this only prints the title of the product page you’re actually on, and not the three selected related product’s titles.
Anyone have any insight?