The maybe_add_existing_user_to_blog() WordPress PHP function adds a new user to a blog by visiting /newbloguser/{key}/
.
Usage
maybe_add_existing_user_to_blog();
Parameters
- None
More information
See WordPress Developer Resources: maybe_add_existing_user_to_blog()
Examples
Add Existing User to Blog
To add an existing user to a blog, you can generate a unique key and store the user’s details in the options table. Then, have the user visit the URL with the generated key.
// Generate a unique key for the user $key = wp_generate_password(20, false); // User data to be added to the blog $user_data = array( 'user_id' => 10, 'role' => 'editor' ); // Save user data as an option update_option("new_user_{$key}", $user_data); // Provide the user with the URL to visit and add themselves to the blog echo "Visit this link to join the blog: " . home_url("newbloguser/{$key}/");
Custom Page to Add Existing User to Blog
Create a custom page template and use the maybe_add_existing_user_to_blog() function to allow existing users to join the blog by visiting a specific URL.
// In your custom page template add_action('template_redirect', 'my_add_existing_user_to_blog'); function my_add_existing_user_to_blog() { if (is_page('join-blog')) { maybe_add_existing_user_to_blog(); } }
Add User to Blog via Custom Function
Create a custom function to add an existing user to the blog by passing the unique key as an argument.
function my_add_existing_user($key) { $_GET['key'] = $key; maybe_add_existing_user_to_blog(); } // Call the custom function with the unique key my_add_existing_user('example_key');
Validate Key before Adding User
Add a custom function to validate the key before adding the user to the blog.
function my_validate_and_add_user($key) { if (my_is_key_valid($key)) { $_GET['key'] = $key; maybe_add_existing_user_to_blog(); } } function my_is_key_valid($key) { // Perform your key validation logic here return true; // Assuming the key is valid } // Call the custom function with the unique key my_validate_and_add_user('example_key');
Redirect User after Adding to Blog
Redirect the user to a specific page after adding them to the blog.
add_action('added_existing_user', 'my_redirect_after_adding_user', 10, 1); function my_redirect_after_adding_user($user_id) { // Redirect to the specified page wp_safe_redirect(home_url('welcome')); exit; }