WordPress: Fatal error: Call to undefined function wp_get_current_user()

So, I’m following the example in the following codex page, https://codex.wordpress.org/Function_Reference/wp_get_current_user, to determine whether a user is logged in or not, from within my plugin, and am getting the above mentioned error message:

$current_user = wp_get_current_user();
if ( 0 == $current_user->ID ) {
    // Not logged in.
} else {
    // Logged in.
}

What am I missing here?

Read More

Additional: What I was hoping to achieve, was to allow the jQuery in my code to function whether a user is logged in or not. But still, if a user is logged out, JQuery does not work:

function getregions_scripts() {
    global $post;
    $tempHost = $_SERVER['HTTP_HOST'];
    if ( in_array( $post->post_name, array( 'homepage', 'home-tests') ) && in_array( $tempHost, array( '192.0.0.0', '192.0.0.1' ) )  ){
      wp_enqueue_script(
      'getregions-script',
      plugin_dir_url(__FILE__) . "assets/getregions.js",
      array('jquery'),
      '1.0',
      true
    );
  }

  wp_localize_script(
    'getregions-script', // this needs to match the name of our enqueued script
    'gymRegions',      // the name of the object
    array('ajaxurl' => admin_url('admin-ajax.php')) // the property/value
  );
}

add_action('init','checkUserExists');
function checkUserExists(){
  $current_user = wp_get_current_user();
  if ( 0 == $current_user->ID ) {
      add_action( 'wp_enqueue_scripts', 'getregions_scripts' );
      add_action( 'wp_ajax_showcountries', 'showcountries_callback' );
      add_action( 'wp_ajax_no_priv_showcountries', 'showcountries_callback' );
      add_action( 'wp_ajax_showcountries_frontend', 'showcountries_frontend' );
      add_action( 'wp_ajax_no_priv_showcountries_frontend', 'showcountries_frontend' );
  } else {
    add_action( 'wp_enqueue_scripts', 'getregions_scripts' );
    add_action( 'wp_ajax_showcountries', 'showcountries_callback' );
    add_action( 'wp_ajax_no_priv_showcountries', 'showcountries_callback' );
    add_action( 'wp_ajax_showcountries_frontend', 'showcountries_frontend' );
    add_action( 'wp_ajax_no_priv_showcountries_frontend', 'showcountries_frontend' );
  }
}

function showcountries_callback() {
}

Related posts

Leave a Reply

1 comment

  1. You have to wrap your code inside an init hook, because the file that contains that function is included later on by wordpress.

    add_action('init','your_function');
    function your_function(){
      $current_user = wp_get_current_user();
      // your code
    }