最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

users - is_user_logged_in() throwing undefined function error

programmeradmin8浏览0评论

I am running this simple conditional statement on my plugin page:

if (! is_user_logged_in()) {
    add_action('init', 's8w_ajax_login_init');
}

It is throwing a fatal undefined function error for is_user_logged_in. Am I missing something? I have several wp globals on the same page. Do I have to call something else for this to work?

I am running this simple conditional statement on my plugin page:

if (! is_user_logged_in()) {
    add_action('init', 's8w_ajax_login_init');
}

It is throwing a fatal undefined function error for is_user_logged_in. Am I missing something? I have several wp globals on the same page. Do I have to call something else for this to work?

Share Improve this question asked Aug 8, 2020 at 23:55 petebolducpetebolduc 1294 bronze badges 3
  • Are you making a browser/form/ajax request directly to a PHP file in your plugin? – Tom J Nowell Commented Aug 9, 2020 at 0:33
  • I think I might be... should the ajax function be on the theme function file? Not quite understanding the question. – petebolduc Commented Aug 9, 2020 at 0:38
  • No it shouldn't, you can't make requests directly to PHP files in themes and plugins, be that via AJAX or another way. It won't work as WP won't be loaded. For AJAX use the REST API to register an endpoint so you have a URL to make requests to, look up register_rest_route – Tom J Nowell Commented Aug 9, 2020 at 0:42
Add a comment  | 

1 Answer 1

Reset to default 2

It's failing because WordPress isn't loaded. Instead of making AJAX requests directly to PHP files in your theme, make them to a REST API endpoint.

For example:

add_action( 'rest_api_init', function () {
        register_rest_route( 'petebolduc/v1', '/test/', array(
                'callback' => 'petebolduc_ajax'
        ) );
} );
function petebolduc( $parameters ) {
    $foo = $parameters['foo'];
    return "foo is " . $foo;
}

With that code, visiting: example/wp-json/petebolduc/v1/test?foo=bar

gives:

"foo is bar"
发布评论

评论列表(0)

  1. 暂无评论