简体   繁体   中英

Wordpress: Fatal error: Call to undefined function is_user_logged_in()

I'm loading a PHP script in a wordpress page but when the script is run I get this:

Fatal error: Call to undefined function is_user_logged_in()

Code that it tries to run:

<?php
if ( is_user_logged_in() == true ) {
  /* Some code */
} else {
 /* Some other code */
}
?>

I tried searching for an answer but I couldn't find a working solution.
From what I found on the internet my script is running outside of wordpress and that's why it can't find the function.

Perhaps you are running the code too early as mentioned here: https://wordpress.org/support/topic/fatal-error-call-to-undefined-function-is_user_logged_in

The problem is that is_user_logged_in is a pluggable function, and is therefore loaded after this plugin logic is called. The solution is to make sure that you don't call this too early.

His solution was to wrap the code in another function which is called on init and can be put in your functions.php file:

function your_login_function()
{
    if ( is_user_logged_in() == true ) {
       /* Some code */
    } else {
        /* Some other code */
    }
}
add_action('init', 'your_login_function');
require_once( wp_normalize_path(ABSPATH).'wp-load.php');

class Your_Plugin_Class {
    private  $is_user_logged_in;

    add_action('init', function(){
        $this-> is_user_logged_in = is_user_logged_in();
        echo 'is_user_logged_in'.$this->is_user_logged_in;
    });

    add_filter('woocommerce_billing_fields-2',array( $this, 'add_billing_field' ));

   }

    public function add_billing_field( $fields = array() ) {
        if ( $this->is_user_logged_in  ){
            echo 'add_billing_field'.$this->is_user_logged_in;
            return $fields;
        }else{
            echo 'add_billing_field'.$this->is_user_logged_in;
        }
    }
}

I've got my answer.

I needed to add this line of code to my php script:

require_once("path/to/wordpress/wp-load.php");

And that did the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM