David Stockdale's Scrapcode

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:

Germany = 13, Pakistan = 2, Czechia = 2, United States = 328, Italy = 6, Singapore = 1, Taiwan = 2, Japan = 8, Iraq = 1, Hong Kong = 7, India = 2, Argentina = 1, Türkiye = 11, United Kingdom = 14, Mexico = 1, Ukraine = 4, China = 5, France = 51, Russia = 39, South Africa = 1, Austria = 1, Hungary = 3, Seychelles = 8, Moldova = 3, Cyprus = 1, Belgium = 1, Switzerland = 1, Denmark = 1, Canada = 2, M

Leave a Reply