0

我是 PHP 编程的新手,我正在尝试自学 WordPress 主题开发以获得乐趣,我正在使用 PhpStorm 作为我的 IDE。

我试图更好地理解 WordPress 的内部运作,但我在某些事情上遇到了障碍。

我创建了一个沙盒插件,用于玩 WordPress。

在我的“wp-content/plugins/sandbox/sandbox.php”文件中,我只是运行基本的 PHP 代码来帮助我习惯与 WordPress 相关的语言。

另外,我使用 Composer 安装了 Kint 和 Whoops 来帮助调试。

现在我已经解决了这个问题,这就是我正在做的事情:

代码 #1

namespace MyDevPlayground\Sandbox;

add_action( 'loop_start', __NAMESPACE__ . '\process_the_string' );
function process_the_string() {

    $current_user = wp_get_current_user();

    $data_packet = array(
        'id'    => $current_user->ID,
        'email' => $current_user->user_email,
        'name'  => array(
            'first_name' => $current_user->user_firstname,
            'last_name'  => $current_user->user_lastname,
        ),
    );

    render_user_message( $data_packet );
}

function render_user_message( array $current_user ) {

    $user_id = $current_user['id'];

    d( "Welcome {$current_user['name']['first_name']}, your user id is { {$user_id} }." );

    ddd( "Welcome {$current_user['name']['first_name']}, your user id is {$user_id}." );
}

当我在上面运行代码 #1 时,一切都很好,并且 Kint 显示的值也很好。

现在对于我遇到的问题,我对 WordPress 不了解:

代码 #2

namespace MyDevPlayground\Sandbox;

add_action( 'loop_start', __NAMESPACE__ . '\check_logged_in_user' );
function check_logged_in_user(){
    $current_user = wp_get_current_user();
    if ( 0 == $current_user->ID ) {
        d('Not logged in');
    } else {
        ddd('Logged in');
    }
}

check_logged_in_user();

当我运行上面的代码 #2 时,Whoops 报告以下错误:

调用未定义的函数MyDevPlaygroundSandbox\wp_get_current_user

出于某种原因,当我运行代码 #1 时,wp_get_current_user()函数加载得很好,但代码 #2 却没有。

如果可能的话,有人可以帮助我理解为什么这是外行的术语吗?

代码 #1 和代码 #2 有什么区别?

为什么wp_get_current_user()函数没有在Code #2中加载,但它在Code #1中?

谢谢您的帮助。

4

1 回答 1

1

当您使用“add_action”命令时,您不能使用函数名来调用该操作,您需要使用如下调用命令:

do_action("check_logged_in_user");

更多信息:https ://developer.wordpress.org/reference/functions/add_action/

于 2020-11-10T05:04:57.190 回答