WordPress获取当前用户代码是否有误?插件开发中的代码调用疑问
Hey there! Let's tackle your two questions about WordPress user retrieval code clearly:
问题1:无法判断某段获取当前用户的代码是否有错误
Since you haven't shared the specific code snippet you're working with, it's hard to pinpoint exactly where things might be going wrong. But here are some common pitfalls to check for when retrieving the current user in WordPress:
- Calling the function too early: If you're trying to get the user before WordPress has finished initializing (e.g., in a theme's
functions.phpwithout hooking intoinitorwp_loaded), the user data won't be available yet. Always ensure you're running user-related code after the authentication process is complete. - Confusing functions: Mixing up
get_current_user()(a legacy function) andwp_get_current_user()(the modern, recommended function) can lead to unexpected behavior. - Missing global declaration: If you're relying on the global
$current_uservariable, you need to explicitly declare it withglobal $current_user;before using it.
If you share the exact code you're struggling with, I can give you a more precise diagnosis!
问题2:调用get_current_user()不赋值是否属于错误?
Great question—let's break this down step by step:
First, your proposed code global $current_user = wp_get_current_user(); is actually syntactically incorrect. In PHP, you can't assign a value while declaring a global variable in the same line. The correct way to do this would be:
global $current_user; $current_user = wp_get_current_user();
Now, about the author's choice to call get_current_user() without assigning the return value:
- The
get_current_user()function is a legacy WordPress function whose primary purpose is to initialize the global$current_uservariable. If the author had already declaredglobal $current_user;before calling this function, then afterget_current_user()runs, the global$current_userwill hold the current user's data, so they can use it later without assigning it directly. - That said, this is an outdated approach. The modern, recommended practice is to use
wp_get_current_user()directly, which returns aWP_Userobject (or aWP_Errorif something goes wrong) without relying on global variables. This is safer because it avoids potential conflicts with other code modifying the global$current_user.
So to sum up: the author's code isn't necessarily an error if they're using the global variable afterward, but it's not the best practice. Your instinct to use wp_get_current_user() is correct—you just need to fix the syntax for the global declaration.
内容的提问来源于stack exchange,提问作者learnwithyan

