• If a condition is met, I want to redirect to another page of the same site.

    e.g.
    IF ( condition is true ){ go to this page } else { do nothing and stay on the same page }

    Pls note its for a code snippet I am trying to write.
    NOT interested in other plugins or .htaccess.

    cheers.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Anonymous User 14808221

    (@anonymized-14808221)

    You can use the wp_redirect() function for this kind of task/code.

    An example PHP Code (freely taken from the examples of that Documentation page):

    function my_logged_in_redirect() {
         
        if ( is_user_logged_in() && is_page( 12 ) ) 
        {
            wp_redirect( get_permalink( 32 ) );
            die;
        }
         
    }
    add_action( 'template_redirect', 'my_logged_in_redirect' );

    Above code will do this:
    IF the user is logged in, AND it is page ID 12
    THEN redirect to the page with ID 32
    THEN stop redirection to avoid infinite redirect

    Of course, you will have to adopt this code to the precise condition and redirection you want for your case.

    Note, often there is no need to code an ELSE case, unless, in the IF case the ELSE case is not already excluded.
    This means, if for example you want to redirect if the user is logged in, but ELSE want to do something completely different than NOT redirect, you would have to code an else statement as well.

    Let me know if this helps for a starter!

    Moderator bcworkz

    (@bcworkz)

    Note that wp_redirect() (and any other kind of PHP redirect) only works if done before any output has begun. Doing so from ‘template_redirect’ like Beda had shown is fine. Trying to do so from an actual template will result in a “headers already sent” error. Not a very informative message for this sort of problem. PHP redirects are implemented by sending a Location: header. By sending normal output, we’ve signaled that we’re done with headers. So when we try to send a location header after normal output has started, PHP essentially tells us “You’ve already sent all of your headers, it’s too late now.”

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to redirect to another page via php custom code’ is closed to new replies.