Support

Account

Home Forums General Issues Looping other cpt posts with the same relationship selected.

Helping

Looping other cpt posts with the same relationship selected.

  • Hi,

    I am struggling to output other posts, within the same post type based on whether they have the same relationship field selected, and wondered if you would be able to help please?

    I have two custom post types ‘sessions’ and ‘projects’. Each session post has an ACF relationship field to which project it is connected to (Limited to 1). I would like to output other ‘sessions’ on the single-sessions.php tempalte with the same relationship to projects selected. The relationship acf field on a session is called select_project_if_this_is_related
    i.e 3x sessions all have the selection of the same ‘project’. I have tried to use the doctors/locations example https://www.advancedcustomfields.com/resources/querying-relationship-fields/ but I can’t get it to output anything with the code I am using.

    
    <?php
                $sessions = get_posts(array(
                    'post_type' => 'sessions',
                    'meta_query' => array(
                        array(
                            'key' => 'select_project_if_this_is_related', // name of custom field
                            'value' => '"' . get_the_ID() . '"', // matches exactly "123", not just 123. This prevents a match for "1234"
                            'compare' => 'LIKE'
                        )
                    )
                ));
                ?>
                <?php if( $sessions ): ?>
    
                    <ul>
                        <?php foreach( $sessions as $session ): ?>
                            <?php the_title(); ?>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
    

    What am I doing wrong here? Thank you.
    Dan

  • You need to use the ID of the related post (the project) in your query instead of the ID of the current post (the session). get_the_ID() is returning the ID of the current post.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.