简体   繁体   English

Wordpress:致命错误:调用未定义函数is_user_logged_in()

[英]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: 我在wordpress页面加载一个PHP脚本,但是当脚本运行时,我得到了这个:

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. 从我在互联网上找到的,我的脚本在wordpress之外运行,这就是为什么它找不到该功能。

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 也许您过早地运行代码如下所述: 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. 问题是is_user_logged_in是一个可插入的函数,因此在调用此插件逻辑后加载。 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: 他的解决方案是将代码包装在另一个在init上调用的函数中,并且可以放在functions.php文件中:

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: 我需要将这行代码添加到我的php脚本中:

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

And that did the trick. 这就是诀窍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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