Support

Account

Home Forums General Issues Beer + Location: Tracking Relationship Field Add/Removes?

Solving

Beer + Location: Tracking Relationship Field Add/Removes?

  • I have a site with two CPTs: location and beers-on-tap. I’m showing what beers are on-tap at a location with the relationship field. But the problem is I also need to give a notification when a beer is removed/added during the evening. I’m not seeing a timestamp/field that essentially records when relationships are added/removed.

    Is there a better way to architect this relationship so that if I wanted to track specific beers going on- and off-tap, I could somehow record and present that information as it happens?

  • I don’t understand what kind of notification you want to display/trigger, but you could use the update_value filter to check the difference before saving the new values and notify the way you want on removed/added differences.

    function relation_field_update( $value, $post_id, $field  ) {
        if (wp_is_post_revision( $post_id )) return $value;
    
        $old_values = get_field($field['name']);
        $added = @array_diff($value, $old_values);
        $removed = @array_diff($old_values, $value);
    
        return $value;
    }
    
    add_filter('acf/update_value/name=relation_field', 'relation_field_update', 10, 3);
    

    Where name=relation_field in the filter is the name of the ACF field you want to verify.

    The wp_is_post_revision check is necessary since you don’t want to verify post revision. The @ are there to bypass the exception threw when one of the array is null (this could be done better with condition, e.g. is_array()).

    So, $added will be (empty or) containing the added IDs and $removed will be (empty or) containing the removed IDs.

  • I think something like that might work. Yeah, basically the notification would just be a feed that lists updates to a specific location’s list of beers as they happen. So if a beer is added/removed, then the feed would populate with a new “post” essentially saying what beer was added or removed. Make sense?

    I’m going to try something along these lines and will report back.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Beer + Location: Tracking Relationship Field Add/Removes?’ is closed to new replies.