WordPress Hooks Used
WordPress Hooks Used
This snippet utilizes the WordPress Shortcode API to register and execute dynamic functionality within your site's content. Below is the technical breakdown of the hooks and execution flow.
Shortcode API: add_shortcode
The core of this snippet is built upon the add_shortcode() function. This hook allows you to register a macro ([user_role]) that WordPress will parse and replace with the return value of a specific PHP callback function.
| Parameter | Type | Description |
| :--- | :--- | :--- |
| Tag | string | The shortcode name used in the editor: user_role. |
| Callback | callable | The internal function that retrieves and returns the current user's role. |
Usage Example
Once the code is added to your functions.php file, the hook becomes active. You can trigger the execution by placing the following tag in the Block Editor, Classic Editor, or a Text Widget:
[user_role]
Execution Lifecycle
The execution of this hook occurs within the following WordPress lifecycle stages:
- Registration: When
functions.phpis loaded, theadd_shortcodefunction is called, adding theuser_roletag to the global$shortcode_tagsarray. - Parsing: When a post or page is requested, WordPress runs the
do_shortcode()function during thethe_contentfilter execution. - Callback Execution: If the
[user_role]tag is found, the associated PHP function is executed.- The function calls
wp_get_current_user()to retrieve the current session data. - It accesses the
rolesproperty of theWP_Userobject. - Output: The function returns (rather than echoes) the string to ensure it is rendered correctly within the content flow.
- The function calls
Developer Notes
- Context: This hook only executes on the frontend. If a user is not logged in, the callback typically returns an empty string or a default value, preventing UI breakage for guest visitors.
- Priority: By default, shortcodes are processed after most content filters. If you need to use this within a template file rather than the editor, you must wrap it in the
do_shortcode()function:<?php echo do_shortcode('[user_role]'); ?>