Skip to content

Instantly share code, notes, and snippets.

@andrewlimaza
Created November 5, 2024 08:02
Show Gist options
  • Save andrewlimaza/f3a429fad21e67a3dc65d04480316f44 to your computer and use it in GitHub Desktop.
Save andrewlimaza/f3a429fad21e67a3dc65d04480316f44 to your computer and use it in GitHub Desktop.
Require accounts to be 18 years or older, in order to checkout and signup for a membership level.
<?php
/**
* Require age verification before being able to signup for a membership level.
* Create a Date field in User Fields and rename the $dob_field_name and adjust the $min_age values.
* This supports PMPro V3.2+ and has backwards compatibility, please read the comments.
*
* To add this customization to your site, please follow this guide - 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;
}
if ( isset( $_REQUEST[ $dob_field_name ] ) ) {
$birthday = $_REQUEST[ $dob_field_name ]; // This is a string,
} else {
pmpro_setMessage( 'Please fill out the ' . $dob_field_name . ' field.', 'pmpro_error' );
return false;
}
// Convert Birthday to an array if it is not already.
if ( ! is_array( $birthday ) ) {
$birthday = explode( '-', $birthday );
$birthday = array_combine( ['y', 'm', 'd'], $birthday );
}
// Check if each part of the date is numeric and if it forms a valid date.
if ( ! isset($birthday['m'], $birthday['d'], $birthday['y']) ||
! 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;
}
try {
$now = new DateTime(); // Get the current date.
$dob = new DateTime( $birthday['y'] . '-' . $birthday['m'] . '-' . $birthday['d'] ); // Get the date of birth.
$age = $dob->diff( $now )->y; // Calculate the age of the user.
} catch (Exception $e) {
pmpro_setMessage( 'There was an error processing the date. Please try again.', 'pmpro_error' );
return false;
}
// 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_checkout_user_creation_checks', 'my_pmpro_min_required_age' );
// add_filter( 'pmpro_registration_checks', 'my_pmpro_min_required_age' ); // Use this for all PMPro < 3.2 installations.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment