Created
December 22, 2015 17:30
-
-
Save wpscholar/e686dd83c9a2ae4947f7 to your computer and use it in GitHub Desktop.
A class for handling the addition of custom user registration fields in WordPress.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class WP_Scholar_User_Registration_Field | |
*/ | |
class WP_Scholar_User_Registration_Field { | |
/** | |
* Field name | |
* | |
* @var string | |
*/ | |
public $name; | |
/** | |
* Render callback | |
* | |
* @var callable | |
*/ | |
public $render; | |
/** | |
* Sanitization callback | |
* | |
* @var callable | |
*/ | |
public $sanitize = 'sanitize_text_field'; | |
/** | |
* Validation callback | |
* | |
* @var callable | |
*/ | |
public $validate; | |
/** | |
* Setup actions and filters | |
*/ | |
public function __construct() { | |
add_action( 'register_form', array( $this, 'render' ) ); | |
add_filter( 'registration_errors', array( $this, 'validate' ) ); | |
add_action( 'register_new_user', array( $this, 'save' ) ); | |
} | |
/** | |
* Get the raw value from $_POST | |
* | |
* @return string | |
*/ | |
function get_raw_value() { | |
return trim( filter_input( INPUT_POST, $this->name, FILTER_SANITIZE_STRING ) ); | |
} | |
/** | |
* Sanitize the raw registration field value | |
* | |
* @param string $raw | |
* | |
* @return mixed | |
*/ | |
function sanitize( $raw ) { | |
return is_callable( $this->sanitize ) ? call_user_func( $this->sanitize, $raw ) : null; | |
} | |
/** | |
* WordPress callback for rendering the registration field | |
*/ | |
function render() { | |
if ( is_callable( $this->render ) ) { | |
call_user_func( $this->render, $this ); | |
} | |
} | |
/** | |
* WordPress callback for validating the registration field | |
* | |
* @param WP_Error $errors | |
* | |
* @return WP_Error | |
*/ | |
function validate( WP_Error $errors ) { | |
if ( is_callable( $this->validate ) ) { | |
$errors = call_user_func( $this->validate, $errors ); | |
} | |
return $errors; | |
} | |
/** | |
* WordPress callback for saving the registration field | |
* | |
* @param int $user_id | |
*/ | |
function save( $user_id ) { | |
$raw_value = $this->get_raw_value(); | |
$value = $this->sanitize( $raw_value ); | |
if ( ! empty( $value ) ) { | |
update_user_meta( $user_id, $this->name, $value ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment