Skip to content

Instantly share code, notes, and snippets.

@zackpyle
Created January 30, 2024 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackpyle/6ad0067894cd93bc36b38c48168f7ec2 to your computer and use it in GitHub Desktop.
Save zackpyle/6ad0067894cd93bc36b38c48168f7ec2 to your computer and use it in GitHub Desktop.
Shortcode to return values from a 1:1 ACF relationship
<?php
function acf_relationship_shortcode($atts) {
$atts = shortcode_atts(array(
'name' => '', // ACF field name for the relationship
'display' => '', // ACF field name or WordPress field to display from the related post
'size' => 'full' // OPTIONAL - Size of the featured image (defaults to 'full')
), $atts);
if (empty($atts['name']) || empty($atts['display'])) {
return 'Missing attributes for the shortcode.';
}
$related_posts = get_field($atts['name']);
if (!empty($related_posts)) {
// Since it's a 1:1 relationship, we'll get the first related post
$related_post = $related_posts[0];
// Handling basic WordPress default fields
switch ($atts['display']) {
case 'title':
$field_value = get_the_title($related_post->ID);
break;
case 'url':
$field_value = get_permalink($related_post->ID);
break;
case 'content':
$field_value = apply_filters('the_content', get_post_field('post_content', $related_post->ID));
break;
case 'featured_image':
$field_value = get_the_post_thumbnail_url($related_post->ID, $atts['size']);
break;
default:
// If not a default WP field, get ACF field value from the related post
$field_value = get_field($atts['display'], $related_post->ID);
break;
}
return $field_value;
}
return 'No related posts found.';
}
// Register the shortcode
add_shortcode('acf_relationship', 'acf_relationship_shortcode');
// Shortcode format
// [acf_relationship name="your_relationship_field_name" display="featured_image" size="thumbnail"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment