| 1 | <?php
|
|---|
| 2 |
|
|---|
| 3 | add_action('init', '_state_taxonomy');
|
|---|
| 4 | function _state_taxonomy() {
|
|---|
| 5 | global $wp_rewrite;
|
|---|
| 6 | register_taxonomy('state', array('note', 'post'), array('hierarchical' => true, 'label' => 'States', 'show_ui' => true, 'query_var' => 'state', 'rewrite' => true) );
|
|---|
| 7 | $wp_rewrite->add_rewrite_tag("%state%", '.*?/?([^/]+)', "state="); // Override the query var, do this directly after registering the taxonomy
|
|---|
| 8 | // 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
|
|---|
| 9 | // $wp_rewrite->flush_rules(); // Flush them on activation, not init, please?
|
|---|
| 10 | }
|
|---|
| 11 |
|
|---|
| 12 | add_filter('term_link', '_hierarchical_terms_hierarchical_links', 9, 3);
|
|---|
| 13 | function _hierarchical_terms_hierarchical_links($termlink, $term, $taxonomy) {
|
|---|
| 14 | global $wp_rewrite;
|
|---|
| 15 |
|
|---|
| 16 | if ( 'state' != $taxonomy ) // Change 'state' to your required taxonomy
|
|---|
| 17 | return $termlink;
|
|---|
| 18 |
|
|---|
| 19 | $termstruct = $wp_rewrite->get_extra_permastruct($taxonomy);
|
|---|
| 20 | if ( empty($termstruct) ) // If rewrites are disabled, fall back to the current link
|
|---|
| 21 | return $termlink;
|
|---|
| 22 |
|
|---|
| 23 | if ( empty($term->parent) ) // Fall back to the current link for parent terms
|
|---|
| 24 | return $termlink;
|
|---|
| 25 |
|
|---|
| 26 | $nicename = $term->slug;
|
|---|
| 27 | while ( !empty($term->parent) ) {
|
|---|
| 28 | $term = get_term($term->parent, $taxonomy);
|
|---|
| 29 | $nicename = $term->slug . '/' . $nicename;
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | $termlink = str_replace("%$taxonomy%", $nicename, $termstruct);
|
|---|
| 33 | $termlink = home_url( user_trailingslashit($termlink, 'category') );
|
|---|
| 34 |
|
|---|
| 35 | return $termlink;
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|