<?php

add_action('init', '_state_taxonomy');
function _state_taxonomy() {
	global $wp_rewrite;
	register_taxonomy('state', array('note', 'post'), array('hierarchical' => true, 'label' => 'States', 'show_ui' => true, 'query_var' => 'state', 'rewrite' => true) );
	$wp_rewrite->add_rewrite_tag("%state%", '.*?/?([^/]+)', "state="); // Override the query var, do this directly after registering the taxonomy
	// Note on the regex above, May look strange, but is to only match the final path item in the url, which is the child slug. WP_Query doesnt reconise hierarchical custom tax slugs
	// $wp_rewrite->flush_rules(); // Flush them on activation, not init, please?
}

add_filter('term_link', '_hierarchical_terms_hierarchical_links', 9, 3);
function _hierarchical_terms_hierarchical_links($termlink, $term, $taxonomy) {
	global $wp_rewrite;

	if ( 'state' != $taxonomy ) // Change 'state' to your required taxonomy
		return $termlink;

	$termstruct = $wp_rewrite->get_extra_permastruct($taxonomy);
	if ( empty($termstruct) ) // If rewrites are disabled, fall back to the current link
		return $termlink;

	if ( empty($term->parent) ) // Fall back to the current link for parent terms
		return $termlink;
	
	$nicename = $term->slug;
	while ( !empty($term->parent) ) {
		$term = get_term($term->parent, $taxonomy);
		$nicename = $term->slug . '/' . $nicename;
	}

	$termlink = str_replace("%$taxonomy%", $nicename, $termstruct);
	$termlink = home_url( user_trailingslashit($termlink, 'category') );

	return $termlink;
}

