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?
With just a little more digging, I found my solution: the relationship field is a better solution than trying to dynamically populate a select field and carry post data through it.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.