Child Theme Best Practices
Why Use a Child Theme?
When adding custom functionality to WordPress, it is a best practice to use a Child Theme. If you add the [user_role] shortcode logic directly to your parent theme's functions.php file, your changes will be overwritten and lost whenever the theme developer releases an update.
Using a child theme ensures that:
- Updates are safe: You can update your parent theme without losing the user role functionality.
- Organization: Custom code is kept separate from the core theme logic.
- Debugging: It is easier to troubleshoot issues when custom snippets are isolated in a child theme.
Implementation Steps
To implement this snippet safely within a child theme, follow these steps:
1. Locate your Child Theme Folder
Connect to your site via FTP or use your hosting provider's File Manager. Navigate to:
/wp-content/themes/your-child-theme-folder/
2. Edit functions.php
Open the functions.php file located inside your child theme folder. If the file does not exist, create a new one and ensure it starts with a PHP opening tag:
<?php
// Your child theme logic starts here
3. Append the Snippet
Copy the code from app.php in this repository and paste it at the bottom of your child theme's functions.php file:
/**
* Shortcode to display current user role
*/
add_shortcode('user_role', 'ud_show_user_role');
function ud_show_user_role() {
$user = wp_get_current_user();
$roles = ( array ) $user->roles;
return strtolower(implode(', ', $roles));
}
4. Verify the Shortcode
Once saved, navigate to any Page or Post in your WordPress editor and insert the shortcode:
[user_role]
If you are logged in, the shortcode will now persist across all future theme updates.
Troubleshooting Persistence
If the shortcode stops working after a theme update, verify that your Child Theme is still active under Appearance > Themes. Sometimes a major update may require you to re-activate the child theme.