Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Output an ACF post relationship field type using a shortcode:
* [ca_acf_relationship_field field="field_name"]
* You can also pass `post_id` as an attribute
*
* Works with Post Object and Relationship fields, when the return
* format is both post object and post ID
*
* This code assumes you are copying this into functions.php of
* your child theme.
**/
// Setup the shortcode
add_shortcode( 'ca_acf_relationship_field', 'ca_get_relationship_field' );
function ca_get_relationship_field( $atts ) {
ob_start();
global $post;
$defaults = array(
'post_id' => $post->ID, // Default to the current Post ID.
'field' => '',
);
$args = wp_parse_args( $atts, $defaults );
$related_posts = get_field( $args['field'], $args['post_id'] );
// Check if we have a single post (post object, post ID) or an
// array of posts then convert to array.
if( is_object( $related_posts ) ) {
$related_posts = array( $related_posts );
} else if ( is_scalar( $related_posts ) ) {
$related_posts = array( $related_posts );
}
if ( $related_posts ) {
?>
<ul>
<?php foreach( $related_posts as $related_post ) {
if ( is_scalar( $related_post ) ) {
$related_post = get_post( $related_post );
}
?>
<li>
<a href="<?php echo esc_url( get_permalink( $related_post->ID ) ); ?>"><?php echo esc_html( get_the_title( $related_post->ID ) ); ?></a>
</li>
<?php } ?>
</ul>
<?php
}
return ob_get_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment