WooCommerce 产品永久链接结构使用 add_rewrite_rule() 与父/子/页面

问题描述 投票:0回答:1

我正在尝试自定义 WooCommerce 产品的永久链接结构。

我尝试使用 add_rewrite_rule() 实现解决方案,但没有成功。目前,链接生成为:

  • my-website.com/shop/product/product_name-sku

但我希望它们的结构如下:

  • my-website.com/shop/parent-cat/child-cat/product_name-sku

我正在努力理解如何将 get_terms() 与父类别和子类别合并。

到目前为止我的代码片段:

add_filter('post_type_link', 'custom_product_permalink', 1, 2);

function custom_product_permalink($link, $post) {
    if ($post->post_type == 'product') {
        // Convert the entire URL to lowercase
        return strtolower(home_url('shop/product/' . $post->post_name . '-' . get_post_meta($post->ID, '_sku', true) . '/'));
    } else {
        return $link;
    }
}

add_action('init', 'custom_product_permalink_rewrite_rules');

function custom_product_permalink_rewrite_rules() {
    add_rewrite_rule(
        'shop/product/([^/]+)-([^/]+)/?$',
        'index.php?post_type=product&name=$matches[1]&sku=$matches[2]',
        'top'
    );

    flush_rewrite_rules();
}

我是高级 WordPress 编码的新手,任何指导或帮助将不胜感激。

php wordpress woocommerce url-rewriting permalinks
1个回答
0
投票

可以修改

custom_product_permalink()
函数以查找并包含完整类别 slug(带有父 slug)并排除“product”字符串(这也会更改重写规则):

add_filter('post_type_link', 'custom_product_permalink', 1, 2);

function custom_product_permalink($link, $post) {
    if ($post->post_type == 'product') {
        $cat_tax = 'product_cat';
        // Find the product category IDs
        $cat_ids = wp_get_post_terms($post->ID, $cat_tax, ['fields' => 'ids']);
        $cat_full_slug = '';
        if (is_array($cat_ids) && !empty($cat_ids)) {
            // Build a full hierarchical category slug
            $cat_full_slug = get_term_parents_list($cat_ids[0], $cat_tax, [
                'format' => 'slug',
                'separator' => '/',
                'link' => false,
                'inclusive' =>true
            ]);
        }
        // Convert the entire URL to lowercase
        return strtolower(home_url('shop/' . $cat_full_slug .
                                   $post->post_name . '-' .
                                   get_post_meta($post->ID, '_sku', true) . '/'));
    } else {
        return $link;
    }
}

add_action('init', 'custom_product_permalink_rewrite_rules');

function custom_product_permalink_rewrite_rules() {
    add_rewrite_rule(
        'shop/.+/([^/]+)-([^/]+)/?$',
        'index.php?post_type=product&name=$matches[1]&sku=$matches[2]',
        'top'
    );

    flush_rewrite_rules();
}

请注意,产品应至少有一个类别才能发挥作用。如果有多个类别,则仅使用

wp_get_post_terms()
返回的第一个类别。

© www.soinside.com 2019 - 2024. All rights reserved.