Get Values from a Custom Relationship Field

How to pull records from a related pod through the Relationship Field in a Custom Post Type

This code snippet walks you through the common process for pulling related records from a Relationship field in a Custom Post Type. You can also check out this tutorial for a more detailed analysis about what each step in the code does.

<?php 
    	//get Pods object for current post
    	$pod = pods( 'pod_name', get_the_id() );
	//get the value for the relationship field
	$related = $pod->field( 'relationship_field' );
	//loop through related field, creating links to their own pages
	//only if there is anything to loop through
	if ( ! empty( $related ) ) {
		foreach ( $related as $rel ) { 
			//get id for related post and put in ID
			//for advanced content types use $id = $rel[ 'id' ]
			$id = $rel[ 'ID' ]
			//show the related post name as link
			echo '<a href="'.esc_url( get_permalink( $id ) ).'">'.get_the_title( $id ).'</a>';
			//get the value for some_field in related post and echo it
			$someField = get_post_meta( $id, 'some_field', true );
			echo $someField;
		} //end of foreach
	} //endif ! empty ( $related )
?>

Questions

Leave a Comment