Skip to content

Instantly share code, notes, and snippets.

@ipokkel
Created June 19, 2024 08:48
Show Gist options
  • Save ipokkel/619c17753645d1dae7f52f4a65945754 to your computer and use it in GitHub Desktop.
Save ipokkel/619c17753645d1dae7f52f4a65945754 to your computer and use it in GitHub Desktop.
<?php
/**
* Verify that the user is at least 18 years old before registering.
*
* You can add this recipe to your site by creating a custom plugin
* or using the Code Snippets plugin available for free in the WordPress repository.
* Read this companion article for step-by-step directions on either method.
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function my_pmpro_min_required_age( $okay ) {
$dob_field_name = 'birthday'; // The name of the user field that contains the date of birth.
$min_age = 18; // The minimum age required to register.
// Bail if already not okay
if ( ! $okay ) {
return $okay;
}
// Get the birthday
if ( isset( $_REQUEST[ $dob_field_name ] ) && ! empty( $_REQUEST[ $dob_field_name ] ) ) {
$birthday = $_REQUEST[ $dob_field_name ];
} else {
pmpro_setMessage( 'Please fill out the ' . $dob_field_name . ' field.', 'pmpro_error' );
return false;
}
// Check if the birthday values are numeric and is a valid date.
if ( ! is_numeric( $birthday['m'] ) || ! is_numeric( $birthday['d'] ) || ! is_numeric( $birthday['y'] ) || ! checkdate( $birthday['m'], $birthday['d'], $birthday['y'] ) ) {
pmpro_setMessage( 'Please enter a valid ' . $dob_field_name . '.', 'pmpro_error' );
return false;
}
$now = new DateTime(); // Get the current date.
$dob = new DateTime( $birthday['y'] . '-' . $birthday['m'] . '-' . $birthday['d'] ); // Get the date of birth.
// Calculate the age of the user.
$age = $dob->diff( $now )->y;
// Check if the user is at least 18 years old.
if ( $age < $min_age ) {
pmpro_setMessage( 'You must be at least ' . $min_age . ' years old to register.', 'pmpro_error' );
return false;
}
return $okay;
}
add_filter( 'pmpro_registration_checks', 'my_pmpro_min_required_age' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment