public
Last active

Only lets users with an invite code register for a WordPress site.

  • Download Gist
wp-registration-keys.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
<?php
/*
Plugin Name: WP Invite Codes
Plugin URI: http://pmg.co/
Description: Makes wordpress an invite only community.
Version: n/a
Author: Christopher Davis
Author URI: http://pmg.co/people/chris
*/
 
add_action( 'init', 'wpse15535_add_shortcode' );
function wpse15535_add_shortcode()
{
add_shortcode( 'invite-form', 'wpse15535_invite_form' );
}
 
 
function wpse15535_invite_form()
{
?>
<form action="" method="post">
<input type="hidden" name="wpse15535_action" value="send_invite" />
<input type="text" name="wpse15535_email" />
<input type="submit" value="<?php _e( 'Send Invite' ); ?>" />
</form>
<?php
// Do some stuff if our action is set.
if( isset( $_POST['wpse15535_action'] ) && 'send_invite' == $_POST['wpse15535_action'] )
{
// Get the email
$email = isset( $_POST['wpse15535_email'] ) && is_email( $_POST['wpse15535_email'] ) ? $_POST['wpse15535_email'] : false;
if( ! $email ) return; // bad email? bail.
// generate a random 30 character string.
$key = wp_generate_password( 30 );
// store our keys in the options table
$opts = get_option( 'wpse15535_keys' );
$opts = (array) $opts;
$opts[$email] = $key;
update_option( 'wpse15535_keys', $opts );
// Send an email!
$message = "You're invited to join a sweet community! Click here: " . home_url( 'wp-login.php?action=register&invite_key=' . $key );
wp_mail( $email, "You're invited!", $message );
}
}
 
add_filter( 'registration_errors', 'wpse15535_register_post', 10, 3 );
function wpse15535_register_post( $errors, $login, $email )
{
// bail if something has gone wrong already as they won't be able to register.
if( $errors->get_error_codes() ) return $errors;
// If our key isn't set an error and bail
if( ! isset( $_REQUEST['invite_key'] ) )
{
$errors->add( 'no_key', __( 'You need an invite code to register for this site' ) );
return $errors;
}
$opts = get_option( 'wpse15535_keys' );
// see if this email has a key and if it matches what was submitted.
if( ! isset( $opts[$email] ) || $_REQUEST['invite_key'] != $opts[$email] )
{
$errors->add( 'invalid_key', __( 'Invalid Registration Key' ) );
return $errors;
}
// everything okay? Just return the errors and let it go through.
return $errors;
}
 
add_action( 'register_form', 'wpse15535_add_key' );
function wpse15535_add_key()
{
if( isset( $_GET['invite_key'] ) )
{
echo '<input type="hidden" name="invite_key" value="' . esc_attr( $_GET['invite_key'] ) . '" />';
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.