星期三 , 22 1 月 2025

从分类页url中去除category(包含子分类和分类分页)

重写跳转规则



add_action('init', 'rewrite_category_link');

function rewrite_category_link() {
    // 获得所有分类
    $terms = get_terms(array(
        'taxonomy'   => 'category',
        'hide_empty' => false
    ));

    foreach ($terms as $term) {
        // 重写
        // Supports hierarchical URLs (e.g., parent-category/child-category/)
        if ($term->parent) {
            // 获取到带层级的slug (parent + child)
            $parent_slugs = get_category_parents($term->parent, false, '/', true);
            $full_slug = $parent_slugs . $term->slug;

            // 重写子级分类的跳转规则
            add_rewrite_rule('^' . $full_slug . '/?$', 'index.php?category_name=' . $term->slug, 'top');

            // 重写子级的分页的跳转规则
            add_rewrite_rule('^' . $full_slug . '/page/([0-9]{1,})/?$', 'index.php?category_name=' . $term->slug . '&paged=$matches[1]', 'top');
        } else {
            // 重写顶级分类的规则
            add_rewrite_rule('^' . $term->slug . '/?$', 'index.php?category_name=' . $term->slug, 'top');

            // 重写顶级分类的分页的规则
            add_rewrite_rule('^' . $term->slug . '/page/([0-9]{1,})/?$', 'index.php?category_name=' . $term->slug . '&paged=$matches[1]', 'top');
        }
    }

    // 刷新重写规则
    flush_rewrite_rules(false);
}

从url去除掉category和父级的categroy slug

add_filter('term_link', 'remove_parent_category_slug', 10, 3);

function remove_parent_category_slug($termlink, $term, $taxonomy) {
    // Only apply to categories
    if ($taxonomy === 'category') {
        // Check if the term has a parent
        if ($term->parent != 0) {
            // Get the slug of the current term
            $termlink = home_url('/' . $term->slug . '/');
        }
    }
    return $termlink;
}