Wordpress:致命错误:调用未定义的函数wp_get_current_user()

时间:2016-06-06 10:17:10

标签: javascript php wordpress

因此,我在以下codex页面https://codex.wordpress.org/Function_Reference/wp_get_current_user中关注该示例,以确定用户是否已从我的插件中登录,并且收到上述错误消息:

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

我在这里缺少什么?

附加:我希望实现的目的是允许我的代码中的jQuery在用户是否登录时运行。但是,如果用户注销,JQuery不起作用:

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() {
}

1 个答案:

答案 0 :(得分:2)

您必须将代码包装在init挂钩中,因为包含该函数的文件稍后会被wordpress包含。

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