Site logo

Archived topic

Redirection

12 replies · Started by stardrive on August 16, 2015

Viewing posts 1–13 of 13

Dear Tom,

Please, when a user wants or clicks to go to a specific page (e.g. page1), I want the user to be re-directed to another page (e.g. page2) automatically.

Please, kindly assist

Regards,

Stardrive

Hey Stardrive, you can use this function:

function my_page_redirect()
{
    if( is_page( #ID ) )
    {
        wp_redirect( home_url( '/yourpage/' ) );
        exit();
    }
}
add_action( 'template_redirect', 'my_page_redirect' );

If is a post page just change is_page() for is_single()

The function goes into your child theme functions file.

Jean

Hello Jean,

I will try your code and get back to you

Regards,

Stardrive

Thank you so much, Jean. It is OK now

Regards,

Stardrive

Great function, Jean :)

There's also tons of redirection plugins out there for anyone who doesn't want to use a function - just do a quick Google for "WordPress redirection plugin".

Hi!

I am wondering - can this also be done with the new "Elements" from GeneratePress? I am asking because if possible, I'd prefer to avoid a plugin.

Thanks a lot.

Hi there,

yeah - i can't see why not.
You could use the Custom Hook to apply your function to the template_redirect hook.

Thanks for the quick reply David. I think this would require me some more digging, as I'm a newbie to WP and hooks. I found out that it's better to use wp_safe_redirect instead of wp_redirect, and also the documentation says it's possible to do 301 redirects with that function (https://developer.wordpress.org/reference/functions/wp_redirect/). So that's great in principle. I just don't know how to execute it with GP's Elements hooks :-)

I am using https://en-gb.wordpress.org/plugins/redirection/ for now - the plugin is from an Automattic
employee and has been around for ages and been maintained so it looks like quite a safe bet.

The template_redirect is a Hook so you can add any function ( that is relative ) to that hook. Whether you call the wp_redirect or wp_safe_redirect function it doesn't matter.

Personally i would stick with the plugin as its a lot less aggravation and will have covered all the complexities of 301s etc.

Thanks David. What I meant was that I do not know how/where/what code to put in to the Elements screen - I can see Jean's snippet above but it's not clear to me how to put this into GP Elements.

Anyway I am definitely sticking with the plugin, it's quite great, and as mentioned secure/trustworthy/maintained enough - but might be good to know for reference or future readers how to do it in GP Elements.

Thanks again!

Just tested it - and unfortunately not possible - looks like Tom kept these hooks out of harms way for security reasons.

Thank you for checking, good to know!

You're welcome

This archived topic is closed to new replies.