<?php 

/**
 * Author: MyListing Club
 * Author URI: https://mylisting.club
 */
 

// PERMALINK MANAGER PRO - PART 1 - DO NOT USE PERMALINK MANAGER TO REWRITE REGION TAXONOMY PERMALINKS
function bis_exclude_region_tax($taxs) {
    if(is_array($taxs)) {
        $taxs[] = 'region';
    }
   
    return $taxs;
}
add_filter('permalink_manager_disabled_taxonomies', 'bis_exclude_region_tax');
 
// PERMALINK MANAGER PRO - PART 2 - REWRITE REGION TAXONOMY PERMALINKES WITH REGION PAGES
function bis_rewrite_region_tax_permalinks($link, $term, $taxonomy) {
    if($taxonomy == 'region' && function_exists('get_field')) {
        // A. Use "Custom Landing Page" ACF field
        $region_page = get_field('_landing_page', $term->taxonomy . '_' . $term->term_id);
       
        // B. Find the page with the same slug
        if(empty($region_page)) {
			// BA. Add the parents' slugs
			if(!empty($term->parent)) {
				$term_ancestors = get_ancestors($term->term_id, $taxonomy, 'taxonomy');
				$term_ancestors_slugs = array();
				
				foreach((array) $term_ancestors as $ancestor) {
					$ancestor_term = get_term($ancestor, $taxonomy);
					$term_ancestors_slugs[] = $ancestor_term->slug;
				}
				
				$term_ancestors_slugs = array_reverse($term_ancestors_slugs);
				$term_ancestors_slugs_string = implode('/', $term_ancestors_slugs);
				
				$term_slug = "{$term_ancestors_slugs_string}/{$term->slug}";
			}
			// BB. The term has no ancestors
			else {
				$term_slug = $term->slug;
			}
			
            $region_page = get_page_by_path($term_slug);
        }
       
        // Change the term permalink to page permalink
        if(!empty($region_page->ID)) {
            $link = get_permalink($region_page->ID);
        }
 
    }
   
    return $link;
}
add_filter('term_link', 'bis_rewrite_region_tax_permalinks', 100, 3);