Skip to content

Instantly share code, notes, and snippets.

@bainternet
Forked from chrisguitarguy/wp-registration-keys.php
Created September 23, 2012 18:59
Show Gist options
  • Save bainternet/3772681 to your computer and use it in GitHub Desktop.
Save bainternet/3772681 to your computer and use it in GitHub Desktop.
Only lets users with an invite code register for a WordPress site.
<?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'] ) . '" />';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment