問題描述

我認為以前是一個 out-dated 插件來做到這一點。有什麼辦法可以輕鬆地使用一點代碼嗎?我們更喜歡不依賴於一個插件,因為這使我們依賴開發人員來保持它的 up-to-date 。

我們只有兩個父類,我們要為所有的 child-category 固定鏈接移除:”items” 和”genres”(因此可以定製為僅刪除兩個類別 ID)

我看到有一個單獨的帖子 here 的解決方案,但我不認為這與類別永久鏈接一起工作,是嗎?

最佳解決方案

這個代碼幾乎完成了這個問題的工作,另一個關於從永久鏈接中刪除/category /base 的工作。從一個這樣做的插件得到它,並決定使用原始代碼。

所以固定鏈接只有最低的 child-category 列出。

首先,我們有:

現在…

然而,RSS 提要似乎不適用於這個較短的網址,仍然需要 long-form 網址。 (不知道是否有一個修復。) 此外,它不會更改帖子永久鏈接。這只是變化的類別永久鏈接。將下面的代碼粘貼到你的 functions.php 文件中。我正在使用 Wordpress 3.0+。

// Remove category base
add_filter('category_link', 'no_category_parents',1000,2);
function no_category_parents($catlink, $category_id) {
    $category = &get_category( $category_id );
    if ( is_wp_error( $category ) )
        return $category;
    $category_nicename = $category->slug;

    $catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $category_nicename, 'category' );
    return $catlink;
}

// Add our custom category rewrite rules
add_filter('category_rewrite_rules', 'no_category_parents_rewrite_rules');
function no_category_parents_rewrite_rules($category_rewrite) {
    //print_r($category_rewrite); // For Debugging

    $category_rewrite=array();
    $categories=get_categories(array('hide_empty'=>false));
    foreach($categories as $category) {
        $category_nicename = $category->slug;
        $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
        $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
        $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]';
    }
    // Redirect support from Old Category Base
    global $wp_rewrite;
    $old_base = $wp_rewrite->get_category_permastruct();
    $old_base = str_replace( '%category%', '(.+)', $old_base );
    $old_base = trim($old_base, '/');
    $category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]';

    //print_r($category_rewrite); // For Debugging
    return $category_rewrite;
}

// Add 'category_redirect' query variable
add_filter('query_vars', 'no_category_parents_query_vars');
function no_category_parents_query_vars($public_query_vars) {
    $public_query_vars[] = 'category_redirect';
    return $public_query_vars;
}
// Redirect if 'category_redirect' is set
add_filter('request', 'no_category_parents_request');
function no_category_parents_request($query_vars) {
    //print_r($query_vars); // For Debugging
    if(isset($query_vars['category_redirect'])) {
        $catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['category_redirect'], 'category' );
        status_header(301);
        header("Location: $catlink");
        exit();
    }
    return $query_vars;
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。