Support

Account

Home Forums ACF PRO How do I display a custom field in another custom post type as a shortcode? Reply To: How do I display a custom field in another custom post type as a shortcode?

  • I would do it using PHP in the template.

    The issue is not with showing the content of another post, you can do this by just supplying the post ID in the acf shortcode as long as it’s a field type that can be handled by the acf shortcode

    
    [acf field="field_name" post_id="123"]
    

    The issue is that you want to dynamically populate the post id using the value in the post object field.

    The following is code that should get values, it is just a copy of ACF shortcode with a minor change. It assumes that the field specified is a post object field that only allows one selection.

    
    function related_post_acf_shortcode( $atts ) {
      // extract attributs
      extract( shortcode_atts( array(
        'field'      => '',
        'post_id'    => false,
        'format_value'  => true
      ), $atts ) );
      // get unformatted value of post object field
      $related_post_id = get_field($field, $post_id, false);
      // get value from the related post and return int
      $value = get_field( $field, $related_post_id, $format_value);
      // array
      if( is_array($value) ) {
        $value = @implode( ', ', $value );
      }
      // return
      return $value;
    }
    add_shortcode('related_post_acf', 'related_post_acf_shortcode');