因此,我正在编写一个插件,用于解析 json feed 并从 feed 以编程方式生成页面。我想以编程方式创建一个用户,该用户将成为页面的作者。问题是当我username_exists()在内部调用这个函数时get_user_by(),它最终是未定义的。我的猜测是我需要执行一些操作或需要首先完成一些其他事件,但我不知所措。这是代码,apache 抛出的错误是:
/**
* A simple class for the cron user, ie the 'author' that will
* generate pages from the feed
*/
class PP_CronUser {
private static $cronUserName = 'Cron User';
private static $cronEmail = 'asdf';
private static $cronPW = 'asdf';
private static $ID = null;
public static function getUserID() {
if(!is_null(self::$ID)) return self::$ID;
if(!($id = username_exists(self::$cronUserName))) { //Here's the offending line
self::$ID = $id;
return $id;
}
self::$ID = wp_create_user(self::$cronUserName, self::$cronPW, self::$cronEmail);
return self::$ID;
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
/home/who_cares/wordpress/wp-includes/user.php致命错误:在第 1198 行调用未定义的函数 get_user_by()
sousername_exists已定义,但 thisget_user_by内部调用未定义。有任何想法吗?
这意味着当您尝试调用该函数时 WordPress 核心尚未加载。
一种解决方案是挂钩它:
add_action('init', function() {
$user_id = PP_CronUser::getUserID();
});
Run Code Online (Sandbox Code Playgroud)
因此,您只需调用wp-blog-header.php插件文件的顶部,确保提及正确的路径
require('path/to/wp-blog-header.php');
Run Code Online (Sandbox Code Playgroud)
请注意此致命错误:调用未定义的函数 get_user_by() 错误,当您调用任何未定义的函数或没有该函数的定义时,会发生错误