无法在 WordPress 中使用 add_rewrite_rule 重写产品变体 URL

Can't rewrite product variation URL using add_rewrite_rule in WordPress

我有一个问题,我需要在 WooCommerce 中重写产品的变体 slug。 例如,我有这个 URL:

http://localhost:8888/wordpress/product/wordpress-pennant/?attribute_pa_color=blue

我需要的是这个:

http://localhost:8888/wordpress/product/wordpress-pennant/blue

我试过这段代码,但它不起作用:

add_action( 'init', 'add_rewrite_rules' );
function add_rewrite_rules() {
    add_rewrite_rule(
        '^product/([^/]*)?',
        'index.php?product=$matches[1]&attribute_pa_color=$matches[2]',
        'top'
    );
    add_rewrite_tag('%attribute_pa_color%', '([^&]+)');
}

我不明白我做错了什么,我也刷新了永久链接。

我发现我的代码有错误,所以最后应该是这样的:

add_action( 'init', 'add_rewrite_rules' );
function add_rewrite_rules() {
    add_rewrite_rule('^product/(.+?)/(.+?)/?$', 'index.php?product=$matches[1]&attribute_pa_color=$matches[2]', 'top');
    add_rewrite_tag('%attribute_pa_color%', '([a-zA-Z0-9-]+)');
}