0

I want to set a new Route in WordPress that will be redirected to the desired path by entering a specific pattern.

for example: When I enter any url like below:

http://mywebsite.com/audio/Everything

http://mywebsite.com/audio/**********

http://mywebsite.com/audio/0123456789

These routes and similar ones redirects to sound.php

http://mywebsite.com/wp-content/sounds/sound.php

1 Answer 1

1

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.

1
  • This only works on apache. How can we make a custom route that's agnostic of server software, like nginx? Commented Sep 19 at 17:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.