Support

Account

Home Forums General Issues Getting custom field from related post type

Solving

Getting custom field from related post type

  • Hi all
    I’ve spent all day reading forums & I’m struggling to come up with a solution to this problem.

    I’ve got 2 custom post types:
    People
    Jobs

    Using an ACF relationship, within Jobs I’ve got a field called Job Client (job_client) where we can link the related client/customer.

    What I’d like to display on the job page, is some basic information of the client that gets pulled from the People custom post type. Employer, contact details etc. These are setup as ACF fields.

    So far I’ve got the following code. It displays the standard wordpress fields (title, permalink) fine, but I’m struggling with the ACF fields. Any help/advice would be appreciated.

    $client = get_field(‘job_client’); // your Relationship field

    if( $client ) {
    foreach( $client as $post) {
    setup_postdata($post);
    get_the_title();
    get_the_permalink();
    get_field(’employer’);

    echo “

  • <a href='”;
    the_permalink($post->ID);
    echo “‘>”;
    echo get_the_title($post->ID).'<br>’;
    echo get_field(’employer’->ID).'<br>’;
    if($postdate){
    echo “(date: “;
    echo $postdate;
    echo “)”;
    }
    echo “
  • “;
    // pull whatever you need from the post.
    }
    wp_reset_postdata();
    }

  • Use a reverse relationship query, see example on this page https://www.advancedcustomfields.com/resources/querying-relationship-fields/

    Or set up a bidirectional relationship using a plugin like this one https://wordpress.org/plugins/post-2-post-for-acf/

  • Thanks, I’ve tried your plugin and added a relationship of the same name on the people custom post type.

    Do you have any documentation on how to display the info?

  • I’ve used the following:

    <?php
    $job_client_connect = get_posts(array(
    	'post_type' => 'people',
    	'meta_query' => array(
    		array(
    			'key' => 'job_client', // name of custom field
    			'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
    			'compare' => 'LIKE'
    		)
    	)
    ));
    
    ?>
    <?php if( $job_client_connect ): ?>
    	<table>
    	<?php foreach( $job_client_connect as $job_client_connect ):?>
    		<tr>
    			<td>
    				<a href="<?php echo get_permalink( $job_client_connect->ID ); ?>">
    					<?php echo get_the_title( $job_client_connect->ID ); ?>
    				</a>
    				<p><?php echo get_field('employer', $job_client_connect->ID ); ?></p>
    			</td>
    		</tr>
    	<?php endforeach; ?>
    	</table>
    <?php endif; ?>

    Displays the name & permalink, still not getting the employer ACF info though. It just prints Array below

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

The topic ‘Getting custom field from related post type’ is closed to new replies.