Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active June 6, 2023 04:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklchaves/84176732ef79d273f8dcc5b5f73c7517 to your computer and use it in GitHub Desktop.
Save marklchaves/84176732ef79d273f8dcc5b5f73c7517 to your computer and use it in GitHub Desktop.
The say hello shortcode prints your display name and role if you're logged into a WordPress site. This is great if you need to know who you are logged in as and what role you have for any given post/page you're on.
<?php // Ignore this first line when copying to your child theme's functions.php file.
function say_hello_sc() {
$u = wp_get_current_user();
$display_name = $u->display_name ?: 'there';
$roles = (array) $u->roles ?: ['not logged in'];
return '<p>Yo, <strong>' . $display_name . '</strong> (<em>' . $roles[0] . '</em>)' . '. Thanks for stopping by ;-)</p>';
}
add_shortcode('say_hello', 'say_hello_sc');
/**
* Usage: [say_hello]
*
* Example output:
*
* Yo, Batman (administrator). Thanks for stopping by ;-)
*/
/**
* More field examples:
* $u = get_user_by( 'id', $user_id ); // Can do this for a specific user ID.
* echo $u->user_login;
* echo $u->first_name . ' ' . $u->last_name;
*
* Reference: https://developer.wordpress.org/reference/classes/wp_user/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment