I have a shortcode showing the username of the current user, it works. What I want to do is insert conditions.
if the user has the username show it, otherwise show first name or something else.
I searched on google and here on stack, I understood this is possible thanks to the if and else conditions but I’ve never done it, can someone help me understand how I can insert these conditions in my shortcode?
also I would like to show other information as well, such as e-mail, last name, registration date and the like, is there a documentation / list on where to get all these values?
function display_current_username () {
$user = wp_get_current_user();
$name = $user->display_name;
return $user->display_name;
}
add_shortcode('display_name', 'display_current_username');
2
Answers
If/Else
conditionals are a foundational aspect of PHP. It doesn’t matter really if it’s WP or not, they work the same.To answer the main question, you would add the conditional like this:
All the documentation for the user data object returnd using
wp_get_current_user()
can be found here: https://developer.wordpress.org/reference/functions/wp_get_current_user/#comment-437To get more user data, use the
get_userdata()
functionYou can pass the user id to get all the data:
You can use that in your shortcode as well. Something like this:
get_userdata
is a wrapper/helper forget_user_by()
. Here is the full object returned byget_userdata()
: https://developer.wordpress.org/reference/functions/get_user_by/#comment-495EDIT
Based on question in comment
Try this: