Support

Account

Home Forums General Issues Get posts with Relationship Query

Solving

Get posts with Relationship Query

  • Hi,

    I am trying to create a section at the bottom of my Artwork page that shows related artworks by the same artist.

    Each piece of artwork has a relationship field via custom fields that assigns to an Artist. I would like to show pieces of artwork if they have the same artist.

    Some help with the below example would be greatly appreciated.

    I am stuck with the following:

    
    <?php
    $artworks = get_posts(array(
    	'post_type' => 'artwork',
    	'meta_query' => array(
    		array(
    			'key' => 'artist', // name of custom field
    			'value' => 'name', // matches exaclty "123", not just 123.This prevents a match for "1234" 
    			'compare' => 'natasha_yudina'
    		)
    	)
    ));
    
    ?>
    <?php if( $artworks ): ?>
    	<ul>
    	<?php foreach( $artworks as $artwork ): ?>
    		<?php 
    
    		$image = get_field('image', $artwork->ID);
    
    		?>
    		<li>
    			<a href="<?php echo get_permalink( $artwork->ID ); ?>">
    				<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" width="30" />
    				<?php echo get_the_title( $artwork->ID ); ?>
    			</a>
    		</li>
    	<?php endforeach; ?>
    	</ul>
    <?php endif; ?>
    
    
  • Do you mean how to get the ID or the title of the artist of the current post from the relationship field instead of using a hard coded name like in your example ‘natasha_yudina’ or you want to show only post from ‘natasha_yudina’?

    Either way you are using compare the wrong way I guess. This is purely a wordpress question.

    Change this:

    array(
            'key' => 'artist', // name of custom field
    	'value' => 'name', // matches exaclty "123", not just 123.This prevents a match for "1234" 
    			'compare' => 'natasha_yudina'
    		)

    To this:

    array(
           'key' => 'artist', // name of custom field
            'value' => 'natasha_yudina' // value of custom field
            )
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Get posts with Relationship Query’ is closed to new replies.