Search code examples
phpwordpressplugins

WordPress function is_user_logged_in is not working in siteurl, wp_redirect


I was trying to modify site_URL and wp_redirect with the following code

<?php

add_filter( 'site_url', 'my_prefix_site_url', 10, 2 );
add_filter( 'wp_redirect', 'my_prefix_wp_redirect' );

function my_prefix_site_url( $url, $scheme ) {
    return my_prefix_modify_url( $url, $scheme );
}

function my_prefix_wp_redirect( $url ) {
    return my_prefix_modify_url( $url, null );
}

function my_prefix_modify_url( $url, $scheme = null ) {
    $current_url = isset( $_SERVER['PHP_SELF'] ) ? sanitize_text_field( wp_unslush( $_SERVER['PHP_SELF'] ) ) : '';

    if ( ! strpos( $current_url, 'wp-admin' ) && ! is_user_logged_in() ) {
        return '/';
    }

    return $url;
}

But got the following error.

Fatal error: Uncaught Error: Call to undefined function is_user_logged_in()

After some research I figured out that wp_redirect is called before the pluggable.php file is called which contains is_user_logged_in() function. So I went on to include it in my code as following

if ( ! function_exists( 'is_user_logged_in' ) ) {
    require_once ABSPATH . WPINC . '/pluggable.php';
}

After including this file, the code is working properly but some other plugins are conflicting with it, as they are not able overwrite the pluggable functions.

Short Question: How can I validate if user is logged in at wp_redirect level before pluggable.php is loaded.

Thanks in advance.


Solution

  • I really don't understand what this code's actual purpose is, and I can think of several things it would break if I'm reading it correctly, but to your literal question: just write your own function.

    The function is_user_logged_in isn't very complicated in the default version:

    function is_user_logged_in() {
        $user = wp_get_current_user();
    
        return $user->exists();
    }
    

    And wp_get_current_user is also pluggable but simple:

    function wp_get_current_user() {
        return _wp_get_current_user();
    }
    

    So you'd just write this:

    function custom_is_user_logged_in() {
        return _wp_get_current_user()->exists();
    }