WordPress.org

Ready to get started?Download WordPress

Forums

What hook should you use for wp_redirect? (4 posts)

  1. hq216493
    Member
    Posted 1 year ago #

    I have spent....lets just say a long time trying to solve this one, I'd appreciate any help/advice anyone can offer.

    I'm developing...what was supposed to be a quick plugin, to make it so that users that aren't logged in get redirected to the login page if they try and access certain pages.

    add_action( 'template_redirect', 'restrictPage_blah', 100 );
    
    function restrictPage_blah() {
    if( ! is_user_logged_in() && is_page('restrictedPage') )
    {
    wp_redirect( 'http://www.google.com' );
        exit;
    }
    }

    Unfortunately this doesn't work, after testing with ECHO statements it shows that this is only called once and isn't called when the user navigates to another page.

    The major problem I'm having is trying to identify an appropriate hook for the function to be fired on. It needs to be before the headers are sent but it also needs to be fired on every page change and of course during a point where is_page works.

    I'm sorry to trouble everyone with this but I've been searching around for a few hours and it's kinda driving me crazy.

    Another thing to note is that I'm using a multisite installation that is running the latest version of buddypress with the default buddypress theme.

    Thanks for your time.

    Currently I'm adding this in the header page of the theme:

    <?php
    if(is_page('activity') && ! is_user_logged_in())
    {
    wp_redirect( 'http://www.google.com' );
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    As you can see it has to be placed right at the top before the DOCTYPE tag, this works perfectly BUT any automatic update to the theme and these changes are erased, this post was made purely because I would like this as a plugin, I just thought others may appreciate this "fix" for the time being.

  2. Andre Malan
    Member
    Posted 1 year ago #

    After going through many of them, I found that ""pre_posts" seems to work the most consistently for me on different environments.

    add_action( 'pre_posts', 'restrictPage_blah', 100 );
  3. valuser
    Member
    Posted 1 year ago #

  4. valuser
    Member
    Posted 1 year ago #

    make it so that users that aren't logged in get redirected to the login page

    perhaps this rejig of the above might work:-

    function sh_walled_garden()
    {
    global $bp;
    if( bp_is_register_page() || bp_is_activation_page())
    return;
    if( ! bp_is_blog_page() && ! is_user_logged_in() )
    bp_core_redirect( bp_get_signup_page() );
    }
    add_action( 'wp_loaded', 'sh_walled_garden' );

Topic Closed

This topic has been closed to new replies.

About this Topic