Manual Code Integration
Manual Code Integration
Integrating this snippet manually allows you to enable the user role shortcode without installing an additional plugin. This process involves adding a PHP code block to your WordPress theme.
1. Preparation and Safety
Before modifying your site's files, please follow these best practices:
- Backup your site: Ensure you have a recent backup of your
functions.phpfile or your entire site. - Use a Child Theme: It is highly recommended to add custom code to a Child Theme. If you add code to a parent theme, your changes will be overwritten when the theme updates.
2. Locate your functions.php file
You can access your theme's functions file in two ways:
- Via FTP/SFTP or File Manager: Navigate to
/wp-content/themes/your-child-theme/functions.php. - Via WordPress Dashboard: Go to Appearance > Theme File Editor and select
functions.phpfrom the right-hand sidebar.
3. Add the Snippet
- Open the
app.phpfile included in this repository. - Copy the entire PHP code block within that file.
- Paste the code at the very bottom of your
functions.phpfile.
Note: If your
functions.phpfile ends with a closing PHP tag (?>), ensure you paste the code before that tag.
// Example of the logic being integrated
add_shortcode('user_role', 'display_user_role_frontend');
function display_user_role_frontend() {
if (is_user_logged_in()) {
$user = wp_get_current_user();
$roles = (array) $user->roles;
return esc_html(ucfirst($roles[0]));
}
return '';
}
4. Verify the Integration
Once the file is saved, you can verify the integration by using the shortcode in any post, page, or widget area.
Usage in Block Editor:
- Open a Page or Post.
- Add a Shortcode block.
- Enter the following:
[user_role] - Publish the page and view it while logged in to see your current role.
Usage in PHP Templates:
If you wish to call this functionality directly within your theme template files, use the do_shortcode function:
<?php echo do_shortcode('[user_role]'); ?>
Troubleshooting
- White Screen/Error: If your site fails to load after saving, there may be a syntax error. Revert the changes via FTP and ensure no duplicate
<?phptags were pasted. - Shortcode displays as text: Ensure the code was pasted into
functions.phpcorrectly and that the theme is currently active.