City-based and Country-based Conditional Output in Bricks

This Pro tutorial provides the steps to render a Bricks element only if the visitor is from the specified country or city.

Note: Caching may affect the way this works. You are advised to first test this solution on your server/site setup.

Step 1

Register a free account at ipinfo.io from https://ipinfo.io/signup.

Free usage of their API is limited to 50,000 API requests per month.

After you verify your email address, make a note of your token from https://ipinfo.io/account/home.

Step 2

Add the following in child theme‘s functions.php or a code snippets plugin:

function bl_get_visitor_country( string $key ): string|bool {
	$token = '12345678901234';

	$ip = $_SERVER['REMOTE_ADDR'];

	$request = wp_safe_remote_get( "https://ipinfo.io/{$ip}?token={$token}" );

	if ( is_wp_error( $request ) ) {
		return false;
	}
	
	$response = wp_remote_retrieve_body( $request );

	$array = json_decode( $response, true );
	// Ex.: https://d.pr/i/fBUIeM

	return $array[$key];
}

Replace 12345678901234 with your token.

Step 3

To use the condition, in Bricks editor apply a Dynamic data condition on the element(s) that should be conditionally output based on the visitor’s country or city.

{echo:bl_get_visitor_country(country)}

Country Code (US in the above screenshot example) should be entered in the last field to check against, not the full country name.

The list of these codes can be seen at https://www.iban.com/country-codes under the “Alpha-2” column.

For UK, it is GB.

To check the visitor’s country, pass city as the argument to the bl_get_visitor_country() function.

{echo:bl_get_visitor_country(country)}

and enter the city name in the last field in the condition. Ex.: Melbourne

Reference

https://ipinfo.io/developers