How to allow WordPress to recognize a custom URL segment after a product URL and use a custom template?

Essentially I'm trying to allow a URL like this:

https://example.com/products/my-product/test

I'm using WooCommerce, my product base is /products, and the product name would be My Product here. I want to allow the URL segment /test and then detect that and redirect to a custom template.

I'm almost there, but I can't get the template_include filter to properly use the custom template.

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

add_action( 'init', function () {
    flush_rewrite_rules(); // for testing only
    $product_base = ltrim( get_option( 'woocommerce_permalinks' )[ 'product_base' ], '/' );
    add_rewrite_rule( {$product_base}/([^/]+)/test, 'index.php?product=$matches[1]test=1', 'top' );
} );

add_filter( 'template_include', function( $template ) {
    if ( get_query_var( 'test' ) ) {
        $template = get_stylesheet_directory() . '/templates/test.php';
    }
 
    return $template;
}, 1, PHP_INT_MAX );

The template_include function is correctly returning the template that I want to use, but when I go to https://example.com/products/my-product/test it just returns the product page.

Topic query-variable rewrite-rules url-rewriting templates posts Wordpress

Category Web


Looks like all I needed to do was put the template_include filter inside of the init action. Source: https://stackoverflow.com/a/50037707/5749974

add_action( 'init', function () {
    $product_base = ltrim( get_option( 'woocommerce_permalinks' )[ 'product_base' ], '/' );
    add_rewrite_rule( "{$product_base}/([^/]+)/test", 'index.php?product=$matches[1]&test=1', 'top' );

    add_filter( 'template_include', function( $template ) {
        if ( get_query_var( 'test' ) ) {
            $template = get_stylesheet_directory() . '/templates/test.php';
        }
     
        return $template;
    } );
} );

Now https://example.com/products/my-product and https://example.com/products/my-product/test both load correctly!

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.