WordPress URL rewrite for WooCommerce attributes

后端 未结 1 1896
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 22:56

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/racquet

相关标签:
1条回答
  • 2020-12-06 23:33

    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;
    
    0 讨论(0)
提交回复
热议问题