ACF relationship field with multiple values not returning any values in shortcode

26 Views Asked by At

I have 2 custom post types: guest and video. They are related many-to-many through the "rel_guest_video" relationship field. The relation is BIDIRECTIONAL and I discovered that bidirectionality only works when the relationship field in both post types has the same slug and I have made it so.

I know that bidirectionality works because I have tested it. The fact that the field is set up for bidirectionality may not even be important, but I am having the hardest time figuring out why my shortcode doesn't work, so I'm mentioning it just in case.

Here is my shortcode. For testing purposes, I've hard-coded a 'video_id' that I know exists and should return two related guests. But, I just keep getting the "No related guests found" error.

When I debug out $related_guests I don't get anything. No errors, no values.

Is the fact that the rel_guest_video field is bidirectional what is causing the problem?

Shortcode [related_guest_info] showing "No related guests found"

// Register the shortcode
add_shortcode('related_guest_info', 'related_guest_info_shortcode');

// Define the shortcode function
function related_guest_info_shortcode($atts) {
    // Extract shortcode attributes
    $atts = shortcode_atts(array(
        'video_id' => 12834, // Default value
    ), $atts, 'related_guest_info');

    // Ensure video_id is set and numeric
    if (!empty($atts['video_id']) && is_numeric($atts['video_id'])) {
        // Query related guests using ACF relationship field
        $related_guests = get_field('rel_guest_video', $atts['video_id']);
        ?>
        <pre style='background:bisque'><?php print_r($related_guests); ?></pre>
        <?php

        // Output guest info
        if ($related_guests) {
            foreach ($related_guests as $guest) {
                $first_name = get_field('first_name', $guest->ID);
                $last_name = get_field('last_name', $guest->ID);
                
                // Display guest info
                echo '<div class="guest-info">';
                echo 'First Name: ' . $first_name . '<br>';
                echo 'Last Name: ' . $last_name . '<br>';
                echo '</div>';
            }
        } else {
            echo 'No related guests found.';
        }

        // Reset post data
        wp_reset_postdata();
    } else {
        echo 'Invalid video ID.';
    }
}
1

There are 1 best solutions below

0
imhvost On

If I understand correctly, the rel_guest_video field is a relationship i.e. an array.

The "Relation" field will return an array of elements where each element is either a WP_Post object or an integer value depending on the return format set.

So find the necessary post $related_guest in the array, and then $related_guests is already attacheds to it. All in all - it just guesswork, as I don't see how you have it all set up there, and you only provide a piece of code.