【问题标题】:Wordpress: Fatal error: Call to undefined function wp_get_current_user()Wordpress:致命错误:调用未定义的函数 wp_get_current_user()
【发布时间】:2016-06-06 10:17:10
【问题描述】:

因此,我将按照以下代码页 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() {
}

【问题讨论】:

  • 您的代码什么也没告诉我们。函数什么时候执行,它挂在哪个钩子上。在定义上述核心功能之前,您的代码肯定运行得太早了
  • @theog 你是否包含 wp-blog-header.php 文件?
  • @PieterGoosen 你是对的。我在上面添加了额外的代码,以便更好地说明我希望实现的目标。
  • 你已经有了答案,但实际上最好使用developer.wordpress.org/reference/functions/is_user_logged_in

标签: javascript php wordpress


【解决方案1】:

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

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

【讨论】:

  • 是的,这段代码消除了错误信息。非常感谢。但是我希望实现的如上所述,仍然行不通。
  • 解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2011-09-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 2016-12-11
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多