Home > database >  Getting related ACF fields from ACF relationship type
Getting related ACF fields from ACF relationship type

Time:10-22

I have a custom post type called "item" which contains a color picker field. In another Custom Post Type called "publication" which I have added Relationship field to create an association to item. I am trying to extract the color code from the relationship using get_posts, but have been unsuccessful in doing this.

$related_items = get_posts(array(
    'post_type' => 'item',
    'meta_query' => array(
        array(
            'key' => 'related_item', // name of custom field
            'value' => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
        )
    )
));

Any thoughts to why this isnt working?

CodePudding user response:

There are lots of reasons of why this potentially isn't working so I suggest a more simplified approach.

If you have already created a relationship using ACF then rather than doing a query for all the posts just use the get_field(), https://www.advancedcustomfields.com/resources/get_field/, function within ACF. That should return the post or post id you need. It will also take up fewer resources since that data is already saved to your current post. Then if you used ACF to add your custom color you can use the same get_field() function but pass in the ID of your reference as the second argument.

Example:

// get related item first
$related_item = get_field('related_item');

Depending on how you have set up the ACF field it will provide the post or the ID. If it returns an object, the post, then your next line to get the color would look like:

$related_item_color = get_field('color', $related_item->ID);

Color being the name of field for the related item. If $related_item returns a number then just pass that number into the get_field it is the Posts ID.

$related_item_color = get_field('color', $related_item);

All this assume you are working from the post template or a function that is called from that template.

  • Related