Created
December 22, 2016 09:27
-
-
Save nameDark/18409692bd269dd104f14a4f3483f844 to your computer and use it in GitHub Desktop.
removing category form slug
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter('request', 'change_term_request', 1, 1 ); | |
function change_term_request($query){ | |
$tax_name = 'category'; | |
if( $query['attachment'] ) : | |
$include_children = true; | |
$name = $query['attachment']; | |
else: | |
$include_children = false; | |
$name = $query['name']; | |
endif; | |
$term = get_term_by('slug', $name, $tax_name); | |
if (isset($name) && $term && !is_wp_error($term)): | |
if( $include_children ) { | |
unset($query['attachment']); | |
$parent = $term->parent; | |
while( $parent ) { | |
$parent_term = get_term( $parent, $tax_name); | |
$name = $parent_term->slug . '/' . $name; | |
$parent = $parent_term->parent; | |
} | |
} else { | |
unset($query['name']); | |
} | |
switch( $tax_name ): | |
case 'category':{ | |
$query['category_name'] = $name; | |
break; | |
} | |
case 'post_tag':{ | |
$query['tag'] = $name; | |
break; | |
} | |
default:{ | |
$query[$tax_name] = $name; | |
break; | |
} | |
endswitch; | |
endif; | |
return $query; | |
} | |
add_filter( 'term_link', 'change_term_permalink', 10, 3 ); | |
function change_term_permalink( $url, $term, $taxonomy ){ | |
$taxonomy_name = 'category'; // your taxonomy name here | |
$taxonomy_slug = 'category'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' ) | |
if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url; | |
$url = str_replace('/' . $taxonomy_slug, '', $url); | |
return $url; | |
} | |
add_action('template_redirect', 'change_old_term_redirect'); | |
function change_old_term_redirect() { | |
$taxonomy_name = 'category'; | |
$taxonomy_slug = 'category'; | |
if( strpos( $_SERVER['REQUEST_URI'], $taxonomy_slug ) === FALSE) | |
return; | |
if( ( is_category() && $taxonomy_name=='category' ) || ( is_tag() && $taxonomy_name=='post_tag' ) || is_tax( $taxonomy_name ) ) : | |
wp_redirect( site_url( str_replace($taxonomy_slug, '', $_SERVER['REQUEST_URI']) ), 301 ); | |
exit(); | |
endif; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
Thanks for the code, but I'm getting errors from this part of the code $query['attachment'] & $query['name'] ...
Do you see the same issue?