Child Theme Integration
Why Use a Child Theme?
When adding custom functionality to WordPress, such as the [user_role] shortcode, it is a best practice to use a Child Theme.
If you add the code directly to your parent theme's functions.php file, your changes will be permanently deleted the next time the theme developer releases an update. A child theme acts as a separate layer that inherits the parent theme's features while keeping your custom snippets safe during update cycles.
Implementation Steps
Follow these steps to safely integrate the user role snippet into your site:
1. Locate (or Create) Your Child Theme
Ensure you have a child theme active. You should see a folder for it in /wp-content/themes/your-theme-child/. If you do not have one, you can create it manually or use a "Child Theme Configurator" plugin.
2. Edit the functions.php File
- Open your child theme folder.
- Locate the
functions.phpfile. - Open the file in a text editor or via the WordPress Theme Editor (Appearance > Theme File Editor).
3. Add the Snippet
Copy the code provided in app.php and paste it at the bottom of your child theme's functions.php file:
// Add this to your child theme's functions.php
function wp_show_user_role_shortcode() {
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
return esc_html( ucfirst( $roles[0] ) );
}
return '';
}
add_shortcode( 'user_role', 'wp_show_user_role_shortcode' );
4. Usage in Frontend
Once the code is saved in your child theme, you can display the current user's role anywhere on your site using the shortcode:
- In Gutenberg/Block Editor: Add a "Shortcode" block and enter
[user_role]. - In Classic Editor: Type
[user_role]directly into the post content. - In PHP Templates: Use the following code:
<?php echo do_shortcode('[user_role]'); ?>
Verification
To ensure the integration is working correctly:
- Log in to your WordPress site.
- Navigate to the page where you added the shortcode.
- You should see your assigned role (e.g., "Administrator" or "Subscriber") displayed.
- Switch to a different theme temporarily and switch back; your code will remain intact because it is housed in the child theme.