Managing 'if' and 'else' statements for these many terms, can be inefficient and difficult to maintain in a long run.
I was able to connect 'Towns' and 'Areas' taxonomy terms, using a term field.
1. I added a single line type term field 'town-areas' with the taxonomy for 'Towns' and made the field have multiple instances.
This field will allow you to save the names of all the "Area" terms with each "Town" term so that whenever a particular town is attached to a post, its connected areas terms are also attached to that post.
2. Next, I added a post form to add a new listing post, and in the form, included the "Town" taxonomy field, but no "Area" taxonomy field.
3. In the last step, I added a custom function attached to the 'cred_save_data' hook.
( ref: https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data )
When the form is submitted, this function will get all the attached "Town" terms from the post, then get all the names of the Areas saved in the term field of those terms, and then attach those Area terms, with the created post.
The code snippet below can be included through either Toolset's custom code feature ( ref: https://toolset.com/documentation/adding-custom-code/using-toolset-to-add-custom-code/ ) or through the active theme's "functions.php" file:
add_action('cred_save_data', 'custom_town_area_connect_funct',10,2);
function custom_town_area_connect_funct($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==1234)
{
$town_tax_slug = 'town-taxonomy-slug';
$area_tax_slug = 'area-taxonomy-slug';
$town_area_field_slug = 'town-areas';
$town_terms = get_the_terms( $post_id, $town_tax_slug );
if ( $town_terms && ! is_wp_error( $town_terms ) ) {
$town_term_all_areas = array();
foreach ( $town_terms as $town_term ) {
$town_term_ID = $town_term->term_id;
$town_term_areas = get_term_meta( $town_term_ID, 'wpcf-'.$town_area_field_slug, false);
if(!empty($town_term_areas)) {
$town_term_all_areas = array_merge($town_term_all_areas, $town_term_areas);
}
}
if(!empty($town_term_all_areas)) {
wp_set_post_terms( $post_id, array_unique($town_term_all_areas), $area_tax_slug );
}
}
}
}
Note: In this custom function, you'll replace:
1234: with the ID of your post form
town-taxonomy-slug: with the taxonomy slug for the towns
area-taxonomy-slug: with the taxonomy slug for the areas
town-areas: with the term field slug, used to store the connected Area term names with the Town terms.
I hope this helps and please let me know if any step is not clear.
Note: The custom code examples from our forum are shared to get you started in the right direction. You're welcome to adjust them as needed and for more personalized customization assistance, you can consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/