Skip to content
Advertisement

WordPress query by ACF relationship field

I have a custom post type “building” and another custom post type “architect”. Building are related to architects via an ACF relationship field.

In the single-architect page I want to display a list of the buildings that are associated to that particular architect.

So far I have achieved this by doing the following:

$loop = new WP_Query( array( 'post_type' => 'building', 'paged' => $paged, 'posts_per_page' => -1 ) );
if ( $loop->have_posts() ) : ?>

    <ul>

        <?php while ( $loop->have_posts() ) : $loop->the_post();

            $building_name = get_the_title(); 
            $building_link = get_the_permalink();

            $architects = get_field('architect'); 
            if( $architects ): ?>
                <?php foreach( $architects as $post):?>
                    <?php setup_postdata($post);
                    if( get_the_title() == $architect_name ) { ?>
                        <li><a href="<?php echo $building_link; ?>"><?php echo $building_name ?></a></li>
                    <?php } ?>
                <?php endforeach; ?>

                <?php wp_reset_postdata(); ?>
            <?php endif; ?>

        <?php endwhile; ?>

    </ul>

<?php endif;
wp_reset_postdata();

However this doese not seem very efficient and I am looking to introduce the relationship into the query itself, which I have tried by doing this:

$buildings = get_posts(array(
    'post_type' => 'building',
    'meta_query' => array(
        array(
            'key' => 'architect',
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));

<?php if( $buildings ): ?>
    <ul>
        <?php foreach( $buildings as $building): ?>

            <li><a href="<?php echo get_permalink( $building->ID ); ?>"><?php echo get_the_title( $building->ID ); ?></a></li>

        <?php endforeach; ?>
    </ul>
<?php endif; ?>

Which is not working, it does not return anything…

Can you see what am I doing wrong or do you have any other idea to approach this situation?

Advertisement

Answer

This is the solution that I’m currently using. I looks quite solid to me.

$buildings = new WP_Query(array(
    'post_type'        => 'building',
    'posts_per_page'   => -1,
    'suppress_filters' => 0,
    'meta_query'       => array(
            array(
                'key'      => 'architect',
                'value'    => '"'.$architect_id.'"',
                'compare'  => 'LIKE'
            )
        ),
        'order' => 'ASC',
        'orderby' => 'title',
        'post_status' => 'publish',
    )); 

while ( $buildings->have_posts() ) {
    $buildings->the_post();

    // print title, content, or whatever here.

}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement