Wordpress:为什么在init上初始化主类后我不能使用is_user_logged_in()?

时间:2016-01-02 05:04:20

标签: php wordpress class init

我的插件有一个主类。它正在init操作上实例化。我认为这足以能够使用像is_user_logged_in()这样的Wordpress函数,但我得到一个致命的错误:调用未定义的函数。下面是我的代码(简化)。 请参阅此问题底部的更新。

fd_main.php

<?php
Class Find_Do_For_Anspress{

  private function includes(){
    require_once(FIND_DO_FOR_ANSPRESS_DIR.'fd_echo.php');
  }

}//End class

function find_do_for_anspress() {
    $FDClassStart = new Find_Do_For_AnsPress();

}
add_action('init', 'find_do_for_anspress');

?>

fd_echo.php

<?php
if ( is_user_logged_in() ) {
                $current_user = wp_get_current_user();
                echo $current_user;
        } else {
                echo 'Not logged in!';
        }

?>

错误:Fatal error: Call to undefined function is_user_logged_in() in /home/effilxhy/public_html/WP/wp-content/plugins/find-do-for-anspress/fd_echo.php on line 1

根据提供的答案:

//This returns 'exist'. This is outside the main class on the same script.
function test_fn() {
    if ( function_exists('is_user_logged_in') )
        echo 'exists';
    else
        echo 'doesnt exist';
}
add_action('init', 'test_fn');


//This returns 'doesn't exist'. Why doesn't this work?
function test_fn() {
    if ( function_exists('is_user_logged_in') )
        echo 'exists';
    else
        echo 'doesnt exist';
}

test_fn();

所以我觉得我发现了一些确凿的东西,但我不知道该怎么做。我在类中定义了函数。我使用initwp_headwp_loaded来实例化该课程。在课程定义之后我正在运行Find_Do_For_Anspress::test_fn();。这不起作用。但是,当我运行Find_Do_For_Anspress :: test_fn();在其中一个包含的文件中,它返回&#34; exists&#34;,所以它有效。我尝试了所有上面的动作钩子来实例化我的类,它们都有效。为什么是这样?不同之处在于运行我的类定义下面的函数,而不是在包含文件中运行它。

2 个答案:

答案 0 :(得分:1)

您是否尝试过直接将代码放在类中而不使用require_once?

另外,我认为require_once仅在第一次创建类时包含该文件。

-

我不认为问题是因为该功能是可插拔的。以下代码输出:&#34;存在&#34;

function test_fn() {
    if ( function_exists('is_user_logged_in') )
        echo 'exists';
    else
        echo 'doesnt exist';
}
add_action('init', 'test_fn');

答案 1 :(得分:1)

尝试如下..

add_action( 'wp_head', 'check_user_login' );

function check_user_login() {

    if ( is_user_logged_in() ) {
        echo 'You are in login state'; 
    } else {
        echo 'Sorry..!';
    }

}

请检查hook list

相关问题