我在类别/子类别中遇到slug(URL)问题。现在我有:http://my-page.pl/animal-category/animal-subcategory。我怎样才能删除" animal-category"对于每个子类别?
看起来应该是这样的:
http://my-page.pl/animal-category/
http://my-page.pl/animal-subcategory/
http://my-page.pl/animal-subcategory/single-page
也许这是一个简单的问题,但我无法在任何地方找到答案:)
答案 0 :(得分:0)
检查以下代码,它会对您有所帮助
// Add 'cat_redirect' query variable in query_vars
add_filter('query_vars', 'no_parent_cat_query_vars');
function no_parent_cat_query_vars($query_vars) {
$query_vars[] = 'cat_redirect';
return $query_vars;
}
// Redirect if 'cat_redirect' is set
add_filter('request', 'no_parent_cat_request');
function no_parent_cat_request($query_vars) {
if(isset($query_vars['cat_redirect'])) {
$cat_link = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['cat_redirect'], 'category' );
status_header(301);
header("Location: $cat_link");
exit();
}
return $query_vars;
}
// Remove category
add_filter('category_link', 'category_url_without_parent',1000,2);
function category_url_without_parent($cat_link, $cat_id)
{
$category = &get_category( $cat_id );
if ( is_wp_error( $category ) ) return $category;
$catname = $category->slug;
$cat_link = trailingslashit(get_option( 'home' )) . user_trailingslashit( $catname, 'category' );
return $cat_link;
}
// Add custom category rewrite rule
add_filter('category_rewrite_rules', 'remove_category_parent_rule');
function remove_category_parent_rule($cat_rewrite) {
global $wp_rewrite;
$cat_rewrite=array();
$cat_list=get_categories(array('hide_empty'=>false));
foreach($cat_list as $category) {
$catname = $category->slug;
$cat_rewrite['('.$catname.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$cat_rewrite['('.$catname.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$cat_rewrite['('.$catname.')/?$'] = 'index.php?category_name=$matches[1]';
}
$old_base = $wp_rewrite->get_category_permastruct();
$old_base = str_replace( '%category%', '(.+)', $old_base );
$old_base = trim($old_base, '/');
$cat_rewrite[$old_base.'$'] = 'index.php?cat_redirect=$matches[1]';
return $cat_rewrite;
}