How to Create Custom Route to a page in WordPress

To set up a custom route in WordPress, you can use the add_rewrite_rule() function. This function allows you to specify a regular expression (regex) pattern for matching URLs and a corresponding rewrite rule for redirecting matching URLs to the desired destination.

Below is an example of how you could use this function to create a custom route that redirects URLs with the pattern http://mywebsite.com/audio/* to http://mywebsite.com/wp-content/sounds/sound.php:

add_action( 'init', 'my_custom_route' );
function my_custom_route() {
    add_rewrite_rule( '^audio/(.*)', 'wp-content/sounds/sound.php', 'top' );
}

The first argument to add_rewrite_rule() is the regex pattern for matching URLs. In this case, the pattern is ^audio/(.), which matches any URL that begins with /audio/ followed by any number of characters (represented by the . wildcard).

The second argument to add_rewrite_rule() is the destination URL for redirecting matching URLs. In this case, the destination URL is wp-content/sounds/sound.php.

The third argument to add_rewrite_rule() is the priority of the rewrite rule. In this case, the priority is set to the top, which means that the rule will be applied before any other rewrite rules.

Once you have added this code to your WordPress theme’s functions.php file, you will need to flush the rewrite rules to ensure that WordPress recognizes your custom route. You can do this by going to the WordPress admin dashboard, navigating to Settings > Permalinks, and clicking the “Save Changes” button. This will update the rewrite rules and make your custom route active.