wordpress 中攔截指定分類( category) 到指定的頁面(Page)

WordPress 最直接的方式是使用 template_redirect,偵測目前是否為指定的 Category Archive,如果符合,就 wp_redirect() 到指定的 Page。

例如:

  • category-a/page-a/
  • category-b/page-b/
  • category-c/page-c/

建議做法

將以下程式放到:

wp-content/themes/你的佈景主題/functions.php

或更推薦放在 Code Snippets 或是 WPCode – Insert Headers and Footers + Custom Code Snippets – WordPress Code Manager 的自訂 Plugin 中:

PHP
/**
 * Redirect specific WordPress categories to specific Pages
 */
function custom_category_redirect() {

    if ( ! is_category() ) {
        return;
    }

    $redirects = array(
        'category-a' => '/page-a/',
        'category-b' => '/page-b/',
        'category-c' => '/page-c/',
    );

    $current_category = get_queried_object();

    if ( isset( $redirects[ $current_category->slug ] ) ) {

        wp_safe_redirect(
            home_url( $redirects[ $current_category->slug ] ),
            301
        );

        exit;
    }
}

add_action( 'template_redirect', 'custom_category_redirect' );

例如實際需求

假設:

CategorySlug要導向 Page
Oracleoracle/oracle/
Linuxlinux/linux-guide/
VMwarevmware/vmware/

可以寫成:

PHP
function custom_category_redirect() {

    if ( ! is_category() ) {
        return;
    }

    $redirects = array(
        'oracle' => '/oracle/',
        'linux'  => '/linux-guide/',
        'vmware' => '/vmware/',
    );

    $category = get_queried_object();

    if ( isset( $redirects[ $category->slug ] ) ) {

        wp_safe_redirect(
            home_url( $redirects[ $category->slug ] ),
            301
        );

        exit;
    }
}

add_action( 'template_redirect', 'custom_category_redirect' );

WordPress 的運作流程如下

TeX
https://example.com/category/oracle/

https://example.com/oracle/

https://example.com/category/linux/

https://example.com/linux-guide/

https://example.com/category/vmware/

https://example.com/vmware/

如果 Category 有子分類

如果需求是:

TeX
/category/oracle/
/category/oracle/database/
/category/oracle/ebs/

全部都要導向某一個 Page,則不能只用 is_category() + slug 簡單處理,需要判斷 parent 或使用 cat_ID

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *


內容索引