I have a post type called ‘Writers’ and another post type called ‘Documents’.

I use the Relationship field in Advanced Custom Fields to link a list of Writers (post objects) to a Document. This means that the field is basically an array containing multiple writers (some contain only one).

I have a template in my theme where I display additional information for each Writer inside their individual posts. I would like to display a list of documents they have contributed to (i.e. Posts containing the writer’s name in the relationship field).

I have tried the following query but it doesn’t work:

$item        = 0;
$writerName = get_the_title();

$my_contributions = new WP_Query( array( 
    'post_type'         => 'documents',
    'posts_per_page'    => -1,
    'meta_key'          => 'doc_contributors',
    'meta_value'        => $writerName,
    'meta_compare'      => 'LIKE'
) );

if( $my_contributions->have_posts() ) : 
    while( $my_contributions->have_posts() ) : 
        $my_contributions->the_post();
        $item++;
?>

<div class="list-line margint10 clearfix">
    <?php echo esc_attr( $item ) . ". " ?><a href="https://wordpress.stackexchange.com/questions/213369/<?php the_permalink(); ?>"><?php get_the_title( $my_contributions->ID ); ?></a>
    <br />
</div>

<?php
    endwhile;
endif;
wp_reset_query();

2 s
2

I am updating my complete answer based on your clarification in the comment below. I hope this helps:

<div class="entry-content">

   <h2>Documents written by this writer</h2>
        <?php 
        /*
         *  Query posts for a relationship value.
         *  This method uses the meta_query LIKE to match the string "123" to the database value a:1:{i:0;s:3:"123";} (serialized array)
         */

         $documents = get_posts(array(
                     'post_type' => 'document',
                     'meta_query' => array(
                      array(
                            'key' => 'writer', // name of custom field
                            'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
                            'compare' => 'LIKE'
                                )
                            )
                        ));

                        ?>
        <?php if( $documents ): ?>
             <ul>
             <?php foreach( $documents as $document ): ?>
                <li>
                   <a href="https://wordpress.stackexchange.com/questions/213369/<?php echo get_permalink( $document->ID ); ?>">
                     <?php echo get_the_title( $document->ID ); ?>
                   </a>
                </li>
             <?php endforeach; ?>
            </ul>
      <?php endif; ?>

</div>

Leave a Reply

Your email address will not be published. Required fields are marked *