get_user_by() undefined in wordpress

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:

Read More

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?

Related posts

Leave a Reply

3 comments

  1. 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();
    });
    
  2. 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

  3. 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.