Skip to content

Instantly share code, notes, and snippets.

@rmorse
Last active February 3, 2024 18:31
Show Gist options
  • Save rmorse/22982fe907988359bd10ace36ce790bf to your computer and use it in GitHub Desktop.
Save rmorse/22982fe907988359bd10ace36ce790bf to your computer and use it in GitHub Desktop.
<?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();
}
@contemplate
Copy link

This is perfect! I expanded your concept here: https://gist.github.com/contemplate/167464f3a0de4a8dfad00a8e925d10bd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment