0

I'm using the 'Post 2 Post for ACF' plugin (https://wordpress.org/plugins/post-2-post-for-acf/) to link 2 ACF relationship fields, for 2 different Custom Post Types. Everything is working great but I'm now needing to filter the posts by Custom Taxonomy Term. The code I have below is working to show all posts (example here: https://www.advancedcustomfields.com/resources/relationship/).

<?php

$post_objects = get_field('character-attributes-relationship');

if( $post_objects ): ?>
        <table>
            <?php foreach( $post_objects as $post): // variable must be called $post (IMPORTANT) ?>
                <?php setup_postdata($post);?>
                <tr>
                    <td>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </td>
            <?php if( have_rows('attributes') ): ?>
                <?php while ( have_rows('attribute') ) : the_row(); ?>
                    <td><?php the_sub_field('attribute');?></td>
                <?php endwhile;?>
                <?php else : ?>
                    <td>n/a</td>
                <?php endif;?>
            <?php endforeach; ?>
        </table>
        <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif;

?>

I tried the WP_Query arguments example as well (https://www.advancedcustomfields.com/resources/relationship/), and I get the desired Taxonomy posts...but ALL of the posts with that taxonomy, not just the ones connected by the Relationship Fied:

<?php 
    $ids = get_field('character-attributes-relationship', false, false);

    $the_query = new WP_Query(array(
        'post_type'         => 'attribute',
        'posts_per_page'    => -1,
        'post__in'          => $ids,
        'post_status'       => 'any',
        'orderby'           => 'post__in',
        'tax_query' => array(
            array(
                'taxonomy' => 'stance',
                'field'    => 'slug',
                'terms'    => 'duck',
            ),
        ),
    ));
 ?>

<?php if ( $the_query->have_posts() ) : ?>
    <table>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <tr>
    <td><?php the_title(); ?></td>
        <?php if( have_rows('attributes') ): ?>
            <?php while ( have_rows('attributes') ) : the_row(); ?>
                <td><?php the_sub_field('attribute');?></td>
            <?php endwhile;?>
            <?php else : ?>
                <td>n/a</td>
            <?php endif;?>
    </tr>
    <?php endwhile; ?>
    </table>
    <?php wp_reset_postdata(); ?>
<?php else : ?>
    <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Any help would be greatly appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.