'Wordpress - Trying to create a custom dynamic route but it yields out 404 page

I am using wordpress 5.9. I am trying to create a custom dynamic route using the following code:

    // create logout and release device get routes

add_action('init', function () {
    add_rewrite_rule(
        'logout-device/([0-9]+)/?$',
        'index.php?pagename=logout-device&device_id=$matches[1]',
        'top'
    );
});

add_action('init', function () {
    $query_vars[] = 'device_id';
    return $query_vars;
});

add_action('template_include', function ($template) {
    if (get_query_var('device_id') && get_query_var('device_id') !== '') {
        return get_template_directory() . '/device_logout.php';
    }

    return $template;
});

after flushing permalinks, if I try to visit /logout-device/1 it gives 404 error. I have created the device_logout.php file in the template dir as well.

Please help me point out the detail I am missing here. Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source