Update Taxonomy from Value Stored in Relationship Field

If you’re using a relationship field to a Taxonomy and you want to make sure it updates the Taxonomy accurately, here’s a post_save action hook you can use to update the Taxonomy from a relationship field.

<?php
/**
 * Update Taxonomy With Value Of Field Related To A Taxonomy
 * Takes the value of a single- or multi-select field 'pods_genre' related to the taxonomy 'genre' and updates the taxonomy with the term set in the 'pods_genre' field from the custom post type 'films'.
 */
add_action( 'pods_api_post_save_pod_item_films', 'my_tax_update', 10, 3 );
function my_tax_update( $pieces, $is_new_item, $id ) {
	// get the values of the 'pods_genre' field
	$terms = $pieces[ 'fields' ][ 'pods_genre' ][ 'value' ];
	if ( empty( $terms ) ) {
		// if there is nothing there set $term to null to avoid errors
		$terms = null;
	} else {
		if ( ! is_array($terms) ) {
			// create an array out of the comma separated values
			$terms = explode(',', $terms);
		}
		
		// ensure all values in the array are integer (otherwise the numerical value is taken as a new taxonomy term instead of an ID)
        	$terms = array_map('intval', $terms);
	}
	// Set the term for taxonomy 'genre' with $terms
	wp_set_object_terms( $id, $terms, 'genre', false );
	
}

Questions