Woocommerce-带有儿童猫的商店,类别,定制基地的相同永久链接

时间:2018-06-23 11:30:58

标签: php wordpress url woocommerce url-rewriting

我的woocommerce网站具有以下结构:

  1. / =主页(静态页面)
  2. / products / =商店页面
  3. / products / =类别库
  4. / products /%product_cat%=产品Perma(自定义基础)

产品的网址变为: website.com/products/parent/child/product-permalink

当前“商店页面” abd产品永久链接与“父级猫”一起工作,但子级返回404。

最初,我在我的functions.php中使用了这段代码

add_filter( 'rewrite_rules_array', function( $rules )
{
    $new_rules = array(
        'products/([^/]*?)/page/([0-9]{1,})/?$' => 'index.php?product_cat=$matches[1]&paged=$matches[2]',
        'products/([^/]*?)/?$' => 'index.php?product_cat=$matches[1]',
    );
    return $new_rules + $rules;
} );

容易。今天,我介绍了父母和子女类别。 Snap!

我在SO上找到了以下帖子: Woocommerce rewrite rule for product sub category

但是,这并不能解决问题,我的配置有所不同,因为我的Shop Page也使用/ Products位置。

谁能看到快速解决方案?

非常感谢。

1 个答案:

答案 0 :(得分:0)

这就是窍门,通过-https://gist.github.com/levantoan/fc705c5ae4739e6d87e2ec51b257ea5c#file-set_product_category_base_same_shop_base-php

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' );

简单,嗯;)