Created
October 2, 2025 10:16
-
-
Save davidmutero/786443a099a19bed48137c4ca5c0f8d4 to your computer and use it in GitHub Desktop.
Validate 2-Letter State Field at 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 that the State field (bstate) contains only 2 letters. | |
| * Also adds helper text below the input field at checkout. | |
| * | |
| * 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. | |
| * https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
| */ | |
| /** | |
| * Server-side validation for the State field. | |
| */ | |
| function my_pmpro_validate_state_field( $okay ) { | |
| $field_name = 'bstate'; | |
| $field_label = 'State'; | |
| if ( ! empty( $_POST[ $field_name ] ) ) { | |
| $value = strtoupper( trim( $_POST[ $field_name ] ) ); | |
| // Must be exactly 2 alphabetic characters | |
| if ( strlen( $value ) !== 2 || ! ctype_alpha( $value ) ) { | |
| pmpro_setMessage( "Please enter a valid 2-letter {$field_label} abbreviation (e.g., CA, NY, ON).", "pmpro_error" ); | |
| return false; | |
| } | |
| } | |
| return $okay; | |
| } | |
| add_filter( 'pmpro_registration_checks', 'my_pmpro_validate_state_field' ); | |
| /** | |
| * Front-end helper text below the field. | |
| */ | |
| function my_pmpro_add_state_field_helper() { | |
| ?> | |
| <script> | |
| document.addEventListener('DOMContentLoaded', function() { | |
| var field = document.querySelector('#bstate'); | |
| if (field) { | |
| // Limit to 2 characters max on input | |
| field.setAttribute('maxlength', '2'); | |
| // Add helper message below field | |
| var helpText = document.createElement('small'); | |
| helpText.className = 'pmpro_form_hint'; | |
| helpText.textContent = 'Enter your 2-letter state or abbrev (e.g., CA, NY).'; | |
| field.parentNode.appendChild(helpText); | |
| } | |
| }); | |
| </script> | |
| <?php | |
| } | |
| add_action( 'wp_footer', 'my_pmpro_add_state_field_helper' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment