This reusable Higher Order Component handles asynchronous data fetching in React applications, making it ideal for fetching data from APIs on componen...
Back to Snippets
php
• 40 lines
JavaScript
JavaScript
PHP
WordPress Custom Hook For User Profile Updates
This code snippet provides a custom WordPress hook to update user profiles. It is useful when you need to synchronize user data with external services or perform custom validation. The hook uses WordPress's built-in user profile update function and includes error handling for secure updates. Note that this hook requires the 'manage_options' capability to trigger the update.
Snippet Stats
Lines
40
Characters
1,390
Read
2 mins
/**
* Custom WordPress hook to update user profiles.
*
* @param int $user_id The ID of the user being updated.
* @param array $update The updated user data.
* @return bool True if the update was successful, false otherwise.
* @throws Exception If there is an error updating the user profile.
*/
function custom_update_user_profile( $user_id, $update ) {
// Check if the user has the 'manage_options' capability
if ( ! current_user_can( 'manage_options' ) ) {
throw new Exception( 'You do not have permission to update user profiles.' );
}
// Validate the update data
if ( ! is_array( $update ) || empty( $update ) ) {
throw new Exception( 'Invalid update data.' );
}
// Update the user profile
$update_result = wp_update_user( array_merge( array( 'ID' => $user_id ), $update ) );
// Check if the update was successful
if ( is_wp_error( $update_result ) ) {
throw new Exception( $update_result->get_error_message() );
}
// Trigger the custom hook
do_action( 'custom_user_profile_updated', $user_id, $update );
return true;
}
// Add the custom hook to the WordPress 'profile_update' hook
add_action( 'profile_update', 'custom_update_user_profile', 10, 2 );
// Example usage:
// add_action( 'custom_user_profile_updated', function ( $user_id, $update ) {
// // Custom logic to handle the updated user profile
// } );
Found an issue with this snippet? Help us improve by reporting it. Report it →
Related Snippets
View allThis React code snippet demonstrates a centralized global state management pattern using the Context API, simplifying state access and updates across ...
Add custom sortable admin columns to any post type — render post meta in the admin list table with proper escaping.