WooCommerce类别和子类别的永久链接

时间:2019-02-24 18:09:30

标签: php wordpress redirect woocommerce

我在stackexchanges上找到了此解决方案,以设置像这样的永久链接结构

Product 1: /shop/category/subcategory/product1/
Product 2: /shop/category/product2/

到目前为止,function.php中带有此代码的解决方案适用于产品和子类别,它们现在都具有基本URL“商店”。但是父类别现在显示404页面。

 function wpse_291143_generate_taxonomy_rewrite_rules( $wp_rewrite ) {

    global $wp_rewrite;
    $base = "shop";

    $rules = array();
    $terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false ));

    foreach($terms as $term) {
        $term_children = get_terms( array(
            'taxonomy' => 'product_cat',
            'parent' => intval($term->term_id),
            'hide_empty' => false
            )
        );
        if($term_children) {
            foreach ( $term_children as $term_child ) {
                $rules[$base . '/' . $term->slug . '/' . $term_child->slug . '/?$'] = 'index.php?product_cat=' . $term_child->slug;
            }
        }
    }

    $wp_rewrite->rules = $rules + $wp_rewrite->rules;
    return $wp_rewrite->rules;
}

add_action('generate_rewrite_rules', 'wpse_291143_generate_taxonomy_rewrite_rules');

如何使此代码与父类别一起工作?

类别库:商店

自定义基本网址 / shop /%product_cat%/

1 个答案:

答案 0 :(得分:0)

遇到同样的问题,终于在这里找到了解决方案: https://wordpress.org/support/topic/same-permalink-for-shop-category-custom-base-with-child-cats/

add_filter( 'rewrite_rules_array', function( $rules ) {
    $new_rules = array();
    $terms = get_terms( array(
        'taxonomy'   => 'product_cat',
        'post_type'  => 'product',
        'hide_empty' => false,
    ));
    if ( $terms && ! is_wp_error( $terms ) ) {
        $siteurl = esc_url( home_url( '/' ) );
        foreach ( $terms as $term ) {
            $term_slug = $term->slug;
            $baseterm = str_replace( $siteurl, '', get_term_link( $term->term_id, 'product_cat' ) );
            // rules for a specific category
            $new_rules[$baseterm .'?$'] = 'index.php?product_cat=' . $term_slug;
            // rules for a category pagination
            $new_rules[$baseterm . '/page/([0-9]{1,})/?$' ] = 'index.php?product_cat=' . $term_slug . '&paged=$matches[1]';
            $new_rules[$baseterm.'(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?product_cat=' . $term_slug . '&feed=$matches[1]';
        }
    }

    return $new_rules + $rules;
} );

/**
 * Flush rewrite rules when create new term
 * need for a new product category rewrite rules
 */
function imp_create_term() {
    flush_rewrite_rules(false);;
}
add_action( 'create_term', 'imp_create_term' );