How to redirect url programmatically in wordpress?

by raven_corwin , in category: Third Party Scripts , 2 months ago

How to redirect url programmatically in wordpress?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 2 months ago

@raven_corwin 

To redirect a URL programmatically in WordPress, you can use the wp_redirect() function. Here's a step-by-step guide on how to do this:

  1. Determine the URL you want to redirect to.
  2. Add the following code snippet to your theme's functions.php file or in a custom plugin:
1
2
3
4
5
function custom_redirect() {
    wp_redirect( 'http://example.com/new-url' );
    exit;
}
add_action( 'template_redirect', 'custom_redirect' );


In this code snippet:

  • Replace "http://example.com/new-url" with the actual URL you want to redirect to.
  • The template_redirect action hook ensures that the redirect happens before any content is sent to the browser.
  1. Save the file and visit the URL you want to redirect from. You should be automatically redirected to the new URL specified in the code.


Please note that it's important to use a proper redirect code such as 301 if you are permanently redirecting a URL for SEO purposes. You can add the status code as a second parameter in the wp_redirect() function like this: wp_redirect( 'http://example.com/new-url', 301 );.