Football Pool Register First & Last name

 avatar
unknown
php
2 years ago
2.6 kB
31
No Index
<?php
/**
 * Plugin Name: Football Pool Register First & Last name
 * Description: Add 2 obligated fields where people need to add their real name.
 * Version: 1.0
 * Author: Antoine Hurkmans
 * Author URI: mailto:[email protected]
 * License: MIT
 */

// Save this plugin in the wp-content/plugins folder and activate it //

add_filter( 'plugins_loaded', array( 'FootballPoolRegisterNames', 'init_extension' ) );

class FootballPoolRegisterNames {
	public static function init_extension() {
		add_action( 'register_form', [__CLASS__, 'registration_form_extra_names'], null, 2 );
		add_filter( 'registration_errors', [__CLASS__, 'registration_check_fields'], null, 3 );
		add_action( 'user_register', [__CLASS__, 'registration_save_user'] );
	}
	
	//1. Add fields. Just the basic layout added before the dropdown.
	public static function registration_form_extra_names() {
		$first_name = ( ! empty( $_POST['first_name'] ) ) ? sanitize_text_field( $_POST['first_name'] ) : '';?>
        <p>
            <label for="first_name">Voornaam</label>
            <input type="text" name="first_name" id="first_name" class="input" value="<?php echo esc_attr(  $first_name  ); ?>" size="25" autocomplete="voornaam" required="required">
        </p>
        <?php
    	$last_name = ( ! empty( $_POST['last_name'] ) ) ? sanitize_text_field( $_POST['last_name'] ) : '';?>
        <p>
            <label for="last_name">Achternaam</label>
            <input type="text" name="last_name" id="last_name" class="input" value="<?php echo esc_attr(  $last_name  ); ?>" size="25" autocomplete="achternaam" required="required">
        </p>
        <?php
	}

	//2. Check fields 
	private static function check_field( &$errors, $field, $message ) {
		if ( Football_Pool_Utils::post_string( $field ) === '' ) {
			$errors->add( "{$field}_error", "<strong>Fout:</strong> voer je {$message} in." );
		}
	}

	public static function registration_check_fields( $errors ) {
		// Check the added fields
		self::check_field( $errors, 'first_name', 'voornaam' );
		self::check_field( $errors, 'last_name', 'achternaam' );

		return $errors;
	}

	// 3. Save user metadata
    public static function registration_save_user( $user_id ) {
        if ( isset( $_POST['first_name'] ) && !empty( $_POST['first_name'] ) ) {
            update_user_meta( $user_id, 'first_name', sanitize_text_field( $_POST['first_name'] ) );
        }
        
        if ( isset( $_POST['last_name'] ) && !empty( $_POST['last_name'] ) ) {
            update_user_meta( $user_id, 'last_name', sanitize_text_field( $_POST['last_name'] ) );
        }
    }
}
Editor is loading...
Leave a Comment