在这篇文章中,我将向您展示如何从WordPress分类URL中删除«category»,如何从文章标签URL中删除«tag»,以及如何从分类法URL中删除自定义分类别名。如(«product_cat»):这是主要部分的代码,您可以将其插入您当前的主题functions.php中即可,如果添加代码后没有生效。请到wordpress后台,设置。固定链接页面保存一次就行了。

add_filter('request', 'rudr_change_term_request', 1, 1 );
 
function rudr_change_term_request($query){
 
  $tax_name = 'product_cat'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
 
  // Request for child terms differs, we should make an additional check
  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); // get the current term to make sure it exists
 
  if (isset($name) && $term && !is_wp_error($term)): // check it here
 
    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; // for categories
        break;
      }
      case 'post_tag':{
        $query['tag'] = $name; // for post tags
        break;
      }
      default:{
        $query[$tax_name] = $name; // for another taxonomies
        break;
      }
    endswitch;
 
  endif;
 
  return $query;
 
}
 
 
add_filter( 'term_link', 'rudr_term_permalink', 10, 3 );
 
function rudr_term_permalink( $url, $term, $taxonomy ){
 
  $taxonomy_name = 'product_cat'; // your taxonomy name here
  $taxonomy_slug = 'product_cat'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' )
 
  // exit the function if taxonomy slug is not in URL
  if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url;
 
  $url = str_replace('/' . $taxonomy_slug, '', $url);
 
  return $url;
}

当然。如果你是正式使用的网站更改了网址,请记得做301跳转。下面是代码。将其插入您当前的主题functions.php中即可。

The WordPress Toolbox
Unlimited Downloads: 500,000+ WordPress Themes, Plugins, Templates & Design Assets

教程:从网址中删除分类法别名(分类,标签和自定义分类法等)

DOWNLOAD NOW

add_action('template_redirect', 'rudr_old_term_redirect');
 
function rudr_old_term_redirect() {
 
  $taxonomy_name = 'product_cat';
  $taxonomy_slug = 'product_cat';
 
  // exit the redirect function if taxonomy slug is not in URL
  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;
 
}

 

发表回复