Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ipokkel/aa2ee03957524281137fc185b0ae8e01 to your computer and use it in GitHub Desktop.
Save ipokkel/aa2ee03957524281137fc185b0ae8e01 to your computer and use it in GitHub Desktop.
<?php
/**
* Require user to reside in specific countries to register for specified membership levels.
*
* 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_init_pmpro_allowed_countries_per_level() {
global $allowed_countries;
//specify the countries allowed to signup. The key is the level id.
$allowed_countries = array(
1 => array( 'US' ), // Add the allowed countries for level 1
2 => array( 'US', 'CA' ), // Add the allowed countries for level 2
);
}
add_action( 'init', 'my_init_pmpro_allowed_countries_per_level' );
function my_pmpro_registration_checks_allowed_countries( $continue_registration ) {
global $allowed_countries, $pmpro_msg, $pmpro_msgt;
$country = $_REQUEST['bcountry'];
$level = pmpro_getLevelAtCheckout();
$level_id = intval( $level->id );
//only check if the level has allowed countries specified
if ( array_key_exists( $level_id, $allowed_countries ) && ! in_array( $country, $allowed_countries[ $level_id ] ) ) {
$pmpro_msg = 'Your country of residence is not permitted to register for this level.';
$pmpro_msgt = 'pmpro_error';
return false;
}
return $continue_registration;
}
add_filter( 'pmpro_registration_checks', 'my_pmpro_registration_checks_allowed_countries' );
function my_pmpro_level_expiration_text_allowed_countries( $text, $level ) {
global $allowed_countries, $pmpro_countries;
if ( array_key_exists( $level->id, $allowed_countries ) ) {
$text = $text . ' This level can only be purchased if you reside in the following countries: ';
//code for commas
$i = 1;
$count = count( $allowed_countries[ $level->id ] );
foreach ( $allowed_countries[ $level->id ] as $country ) {
$text = $text . $pmpro_countries[ $country ];
if ( $i < $count ) {
if ( $i == $count - 1 ) {
$text = $text . ', or ';
} else {
$text = $text . ', ';
}
}
$i++;
}
$text = $text . '.';
}
return $text;
}
add_filter( 'pmpro_level_expiration_text', 'my_pmpro_level_expiration_text_allowed_countries', 10, 2 );
@ipokkel
Copy link
Author

ipokkel commented Apr 25, 2025

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