WordPress URL rewrite for WooCommerce attributes

2020-02-01 16:22发布

I'm using WooCommerce with the "YITH WooCommerce Ajax Navigation" plugin to filter brands. The result is a link that appears as https://example.com/products/racquets/tennis-racquets/?filter_brands=47 Ideally, I would like to use https://example.com/products/racquets/tennis-racquets/brands/wilson instead.

I've tried using an Apache mod_rewrite rule such as:

RewriteRule ^products/racquets/tennis-racquets/?filter_brands=47 /products/racquets/tennis-racquets/wilson [QSA,L]

I've also tried writing a function for my functions.php file but that doesn't seem to catch either. Here's a sample of the code I tried using.

function brand_rewrite_rules() {
    add_rewrite_rule( 'products/racquets/tennis-racquets/?filter_brands=47', 'products/racquets/tennis-racquets/wilson', 'top' );
    flush_rewrite_rules();
} 
add_action( 'init', 'brand_rewrite_rules' );

I did try updating my permalink settings but the function did not do anything. Can anyone propose a solution for this?

1条回答
\"骚年 ilove
2楼-- · 2020-02-01 17:02

It's a matter of adding a Rewrite Endpoint:

Adding an endpoint creates extra rewrite rules for each of the matching places specified by the provided bitmask. A new query var with the same name as the endpoint will also be created. The string following the endpoint definition supplies the value for this query var (e.g. "/foo/bar/" becomes "?foo=bar").

<?php
/**
 * Plugin Name: Add a Brand endpoint to the URLs
 * Plugin URI:  http://stackoverflow.com/a/24331768/1287812
 */

add_action( 'init', function()
{
    add_rewrite_endpoint( 'brands', EP_ALL );
});

add_filter( 'query_vars', function( $vars )
{
    $vars[] = 'brands';
    return $vars;
});

/**
 * Refresh permalinks on plugin activation
 * Source: http://wordpress.stackexchange.com/a/108517/12615 
 */
function WCM_Setup_Demo_on_activation()
{
    if ( ! current_user_can( 'activate_plugins' ) )
        return;

    $plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
    check_admin_referer( "activate-plugin_{$plugin}" );

    add_rewrite_endpoint( 'brands', EP_ALL ); #source: http://wordpress.stackexchange.com/a/118694/12615
    flush_rewrite_rules();
}
register_activation_hook(   __FILE__, 'WCM_Setup_Demo_on_activation' );

Then, in the templates use it like:

$brand = get_query_var('brand') ? urldecode( get_query_var('brand') ) : 'Empty endpoint';
echo $brand;
查看更多
登录 后发表回答