I have site where users sign up to a subscription. When the subscription has ended (I can query that using PHP), I want the user to be redirected to the "subscription-ended" page.

My current code looks like this, and it kind of works:

add_action( 'wp_loaded', 'sub_redirect' );

   * This function checks whether the logged in user's trial has expired and redirects them to the correct page.
function sub_redirect() {
    $user         = wp_get_current_user();
    $end_page     = '/subscription-ended';
    $current          = parse_url(home_url($_SERVER['REQUEST_URI']));

    if ( !is_admin() && ! is_wp_error( $user ) && $current['query'] == 'action=logout' ) {
        // make sure this is actually a WordPress user
        if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) && is_user_logged_in() ) {
              // check the subscription
              $subscription_ended = TRUE;
              if ($subscription_ended) {
                  if ($current['path'] !== $end_page) {
                      wp_safe_redirect( $end_page );

The problem I am facing is that this also fires for when the user tries to logout. This means when I click on the link https://example.com/wp-login.php?action=logout, I also get redirected without ever getting logged out.

I am not sure that the "wp_loaded" hook is the correct one in my case, or should I just check for the "wp-login.php" url?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.