ACF relationship fields - get_field values from other post type

前端 未结 3 1442
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 02:23

In my POSTS page (regular post type), I have setup a ACF relationship field. Inside this I can select company name which are all under the post type of directory_listings.

3条回答
  •  再見小時候
    2020-12-18 02:53

    If I understood this correctly this is the same problem than the one I had. In my case I preferred working with shortcodes. Using [acf field="person"] with the field being a relationshipt only gave me the ID of the person, but I was unable to acces their fields. On the other hand, using [acf field="last_name", post_id=[acf field="person"], which would be an ideal solution does not work as the wordpress parser does not allow nested shortcodes.

    that is why I cam up with this very small php solution:

    function import_cf_from_cpt( $atts ) {
        // import custom fields from other custom post types that are connected via a relationship to the calling custom post type
        // shortcode: [import  ]
        // ex [import person last_name] --> Doe
    
        $postID = do_shortcode("[acf field={$atts[0]}]");
        // we use the first attribute to get the ID of the object
        $postField = get_field($atts[1], $postID);
        // next, using the ID we look for the field of the second attribute.
    return $postField;
    }
    add_shortcode( 'import', 'import_cf_from_cpt' );
    

    Placing this in the functions.php file allows to use the shortcode

    [import person last_name] for example, or any other combination to import field values from other posts.

提交回复
热议问题