Last active
March 12, 2025 17:14
-
-
Save davidmutero/9a80e93b2b6e2c29c5b544cdbeed5a3a to your computer and use it in GitHub Desktop.
Validate Select User field in PMPro Checkout
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 | |
/** | |
* Validate a custom dropdown field in PMPro checkout to ensure a valid selection. | |
* | |
* In this gist, if the user selects the option ("SELECT ONE"), an error message is displayed. | |
* IMPORTANT - Remember you need to add this "default" option to your list of options in the select user field. | |
* The script attempts to retrieve the field's label dynamically for a more informative error. | |
* | |
* 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/ | |
*/ | |
/** | |
* Validate a custom dropdown field to ensure a valid selection. | |
* | |
* @param bool $okay Whether registration checks pass. | |
* @return bool Updated validation result. | |
*/ | |
function pmpro_validate_custom_dropdown( $okay ) { | |
$field_name = 'your_dropdown_field'; // Update with actual field name. | |
$field_label = ''; | |
// Check if the dropdown selection is invalid. | |
if ( ! empty( $_POST[ $field_name ] ) && $_POST[ $field_name ] === "SELECT ONE" ) { | |
// Attempt to retrieve the label dynamically. | |
if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) { | |
$html = file_get_contents( $_SERVER['HTTP_REFERER'] ); | |
libxml_use_internal_errors( true ); // Suppress parsing warnings. | |
$dom = new DOMDocument(); | |
$dom->loadHTML( $html ); | |
libxml_clear_errors(); | |
$labels = $dom->getElementsByTagName( 'label' ); | |
foreach ( $labels as $label ) { | |
if ( $label->getAttribute( 'for' ) === $field_name ) { | |
$field_label = trim( $label->textContent ); | |
break; | |
} | |
} | |
} | |
// Set a default fallback if label is not found. | |
if ( empty( $field_label ) ) { | |
$field_label = 'the select dropdown user field'; | |
} | |
pmpro_setMessage( "You must select a valid option for '{$field_label}'.", "pmpro_error" ); | |
return false; | |
} | |
return $okay; | |
} | |
add_filter( 'pmpro_registration_checks', 'pmpro_validate_custom_dropdown' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment