Reputation: 1308
So, I'm writing a plugin that parses a json feed and generates pages programatically from the feed. I want to create a user programatically that will be the author of the pages. The problem is when I call username_exists()
this function internally calls get_user_by()
which ultimately is undefined. My guess is there is some action I need to hook into or some other event that needs to be done first but I'm at a loss. Here's the code, and the error apache is throwing back:
/**
* 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;
}
}
The error:
Fatal error: Call to undefined function get_user_by() in
/home/who_cares/wordpress/wp-includes/user.php
on line 1198
So username_exists
is defined but this calls get_user_by
internally which is not defined. Any ideas?
Upvotes: 3
Views: 10565
Reputation: 17198
It means the WordPress core has not loaded when you try to call that function.
One solution is to hook it:
add_action('init', function() {
$user_id = PP_CronUser::getUserID();
});
Upvotes: 8
Reputation: 64476
Thus you just have to call wp-blog-header.php
in the top of your plugin file make sure you mention the correct path
require('path/to/wp-blog-header.php');
Note this Fatal error: Call to undefined function get_user_by() error occurs when you call any undefined function or there is no definition of the function
Upvotes: 6
Reputation: 1308
I was right in thinking I needed to hook to something. I was calling this method directly from the plugin. Attaching to the admin_menu hook allowed all the necessary libraries to load.
Upvotes: 1