Adding a Geo based Conditional

Using Toolbox it is very easy to add any kind of filter. A location-based filter for instance is very easy to add.

You will need to install a plugin like GeoIP Detectection from the WordPress Repository.

When you’ve done so, you can add the following code to your functions.php or into your own plugin.

<?php

add_action( 'toolbox_add_conditional_options' , 'add_geo_detect', 10, 1 );

function add_geo_detect() {
	toolboxExtender::add_conditional_option(
									// filter name
									'geo_detect',
									// option key and title
									array('key'=> 'geo_check' , 'title' => __('Geo Check', 'textdomain') ),
									// fields that are part of this options settings.
									// No toggling of subfields or forms
									array(
										'query_parameter' => array(
											'type'          => 'text',
											'label'			=> __( 'isoCode to check for', 'textdomain' ),
											'default'		=> 'US',
										),
									)
								);

  add_filter( 'geo_detect' , 'check_geo_location' , 10, 3 );
  
	function check_geo_location ( $is_visible, $param , $node ) {
		$record = geoip_detect2_get_info_from_current_ip();
		if ( $record->country->isoCode !== strtoupper($param['query_parameter']) ) return false;
	    return $is_visible;
	}
  
}

You will be able to select the conditional from the dropdown list. By default it will check if the isocode is US, but you can check on any other isoCode. A complete list of isocodes can be found here.

Of course you can write your settings and conditional to check for multiple isocodes but this should get you started.

Beaverplugins

Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife. Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.

Leave a Comment