Skip to content

Instantly share code, notes, and snippets.

@JarrydLong
Last active April 3, 2021 02:57
Show Gist options
  • Save JarrydLong/814be0958bd39360655b0bc5029e19e0 to your computer and use it in GitHub Desktop.
Save JarrydLong/814be0958bd39360655b0bc5029e19e0 to your computer and use it in GitHub Desktop.
<?php
/**
* This recipe will validate a UK postal code when submitting on checkout.
* Validation will only occur if the billing country has been set to the UK.
*
* 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 mypmprouk_scripts(){
$ajaxurl = admin_url( 'admin-ajax.php' );
$nonce = wp_create_nonce( 'pmprouk_validate_postcode' );
?>
<script>
var $ = jQuery;
var form = $('#pmpro_form, .pmpro_form');
$( '.pmpro_form' ).submit( function( event ) {
event.preventDefault();
var postal_code = $( '#bzipcode' ).val();
var country = $( '#bcountry' ).val();
var data = {
action: 'pmprouk_validate_postcode',
security: '<?php echo $nonce; ?>',
postal_code: postal_code,
country: country
}
jQuery.post( '<?php echo $ajaxurl; ?>', data, function( response ){
response = JSON.parse( response );
if( response.status == 200 ){
//Valid postal code
this.submit();
return true;
} else if( response.status == 404 ) {
$( '#pmpro_message' ).text( 'Invalid Postal Code Entered' ).addClass( 'pmpro_error' ).removeClass( 'pmpro_alert' ).removeClass( 'pmpro_success' ).show();
return false;
} else {
this.submit();
return true;
}
});
});
</script>
<?php
}
add_action('wp_footer', 'mypmprouk_scripts');
function mypmprouk_validate_postcode(){
check_ajax_referer( 'pmprouk_validate_postcode', 'security' );
if( !empty( $_REQUEST['postal_code'] ) && !empty( $_REQUEST['country'] ) ){
if( $_REQUEST['country'] == 'GB' ){
$postal_code = sanitize_text_field( $_REQUEST['postal_code'] );
$request = wp_remote_get( 'https://api.postcodes.io/postcodes/'.$postal_code );
$response = wp_remote_retrieve_body( $request );
if( !is_wp_error( $response ) ){
echo $response;
} else {
echo '{"status":404,"error":"Invalid postcode"}';
}
} else {
echo '{"status":999,"error":"Invalid Country"}';
}
}
wp_die();
}
add_action( 'wp_ajax_pmprouk_validate_postcode', 'mypmprouk_validate_postcode' );
add_action( 'wp_ajax_nopriv_pmprouk_validate_postcode', 'mypmprouk_validate_postcode' );
@laurenhagan0306
Copy link

This recipe is included in the blog post on "Adding UK Postal Code Validation to Your Website’s Checkout Form" at Paid Memberships Pro here: https://www.paidmembershipspro.com/uk-postal-code-validation-at-checkout/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment