Improved Country Counter

New and improved function for counting the amount of comments from various countries.

Now stores also stores the information by updating an existing row within an existing database table named “locations”.

/**
 * Adds the "location_list" shortcode.
 * [location_list]
 */
add_shortcode('location_list', 'location_list_shortcode');
/*
 * Lists locations I have recieved comments from.
 * 
 * Also stores it in the "locations" table.
 */
function location_list_shortcode() {
	$list_of_locations1 = array();
	$comments = get_comments();
	//LOOP THROUGH COMMENTS CHECKING LOCATIONS
	for($a = 0; $a < count($comments); $a++) {
		//TOO MANY REQUESTS IN 1 MINUTE GETS YOU BLOCKED FROM USING GEOPLUGIN FOR 1 HOUR!!
		//if a is a multiple of 50 then wait 1 minute
		if($a % 50 == 0) {
			// sleep for 60 seconds
			sleep(60);
		}
		$comment = $comments[$a];
		$comment_ip = $comment->comment_author_IP;
		$geopluginURL = 'http://www.geoplugin.net/php.gp?ip=' . $comment_ip;
		$geoip_response = unserialize( file_get_contents( $geopluginURL ) );
		if ( ! empty( $geoip_response ) ) {
			$location = $geoip_response['geoplugin_countryName'];
			$list_of_locations1[] = $location; 
		}
	}
	//creates array of unique names and how often they were used
	$locations_without_duplicates = array_count_values($list_of_locations1);
	//splits the array into names and numbers
	$names = array_keys($locations_without_duplicates);
	$values = array_values($locations_without_duplicates);
	$resultz = "";
	//combines the 2 arrays into a single string.
	for($b = 0; $b < count($names); $b++) {
		if($b != 0) {
			$resultz .= ", ";
		}
		$resultz .= $names[$b];
		$resultz .= " = ";
		$resultz .= $values[$b];
	}
	//Updates the 1 row in the locations table
	global $wpdb;
	$sql = "UPDATE `locations` SET `location`='";
	$sql .= $resultz;
	$sql .="' WHERE `location` IS NOT NULL;";
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
	//return result string.
	return $resultz;
}

Once stored this row can be quickly accessed and displayed to visitors of the site using this simple shortcode.

/**
 * Adds the "read_locations" shortcode.
 * [read_locations]
 */
add_shortcode('read_locations', 'read_locations');


/**
 * Reads the rows of the "locations" table.
 */
function read_locations() {
	global $wpdb;
	$row = $wpdb->get_results("SELECT * FROM `locations` LIMIT 1");
	$result = $row[0];
	return implode(get_object_vars($result));
}

As seen here:

Russia = 38, France = 26, United States = 91, Germany = 4, Poland = 2, Turkey = 1, Austria = 1, Hungary = 3, United Kingdom = 5, India = 2, Moldova = 3, Australia = 2, Cyprus = 1, Belgium = 1, South Africa = 1, Switzerland = 1, Hong Kong = 2, Denmark = 1,

Leave a Reply

%d bloggers like this: