wordpresshttp-redirect

Wordpress redirect specific link to custom link


I have a wordpress website and I want to redirect a specific link to my custom link. I do not want to use any plugin and want to achieve this by writing code in functions.php file. The code that I tried is writen below

function custom_redirect() {
    if(is_page(7)) {
        wp_redirect('http://example.com/my-account/orders/', 301);
        exit();
    }
}
add_action ('template_redirect', 'custom_redirect');

Now the page, ( (is_page(7)) ), from which I want to redirect the users has the url which is http://www.example.com/my-account/ and I want to redirect them to http://www.example.com/my-account/orders. I tried the site_url('/my-account/') function also but unable to achieve that.


Solution

  • The problem is when you test for is_page('my-account') it will return true even when you are viewing an WooCommerce account endpoint. The workaround is to check the global $wp variable for the requested page slug.

    function custom_redirect() {
        global $wp;
    
        if( $wp->request == 'my-account' ) {
            wp_redirect( site_url( 'my-account/orders/' ) );
            exit;
        }
    }
    
    add_action ('template_redirect', 'custom_redirect');