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

Question

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' ], "https://wordpress.stackexchange.com/" );
    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.

in progress 0
Timothy Fisher 2 weeks 2021-11-12T23:08:34-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-11-15T12:25:09-05:00

    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!

Leave an answer

Browse
Browse