add_rewrite_rule working in parent theme but not in child theme

Viewed 72

I have created a CPT and created add rewrite rule using the following code to achieve the following URL structure:

https://www.example.com/coupons/company/

function custom_rewrite_basic() 
{
    add_rewrite_rule('^coupons/([a-z0-9-]+)[/]?$', 'coupons/?host=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');

add_action( 'template_include', function( $template ) {
    if ( get_query_var( 'host' ) == false || get_query_var( 'host' ) == '' ) {
        return $template;
    }
 
    return  get_theme_file_path().'/list-coupons.php';
} );

I have placed the above code in functions.php of child theme but I get a 404 error. The same code worked when successfully when I had uploaded this code in functions.php file of parent theme.

Note: list-coupons.php file exists as a custom template in child theme.

Can anyone help me solve this issue?

1 Answers

WordPress's get_query_var() function just retrieves just the values of its native query variables in the WP_Query class.

Thus, before your add_action( 'template_include'... you will have to add your custom query variable 'host' manually to the array of public query variables like this:

function themeslug_query_vars( $qvars ) {
    $qvars[] = 'host';
    return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' );

This condition has always been true:

if ( ... || get_query_var( 'host' ) == '' ) {
 return $template;
}

And so you always got the default template path in return. Which produced the 404, when placing your code in child theme's functions.php.

Because that default template can just be found at the returned path inside the parent theme.

Related