Counting Comments From Countries

I finally figured out how to automatically generate a list of countries that users have commented from along with how many have come from each.

This can be accomplished simply by adding this code to functions.php and then using the shortcode.

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

/*
 * Lists locations I have recieved comments from.
 * 
 * How should I store this info so it can be quickly displayed to the user?
 * 
 * database? (have a single string in a table, 
 * have a function which updates that specific row)
 * 
 */
function location_list_shortcode() {
	$list_of_locations1 = array();
	
	$comments = get_comments();
	
	//LOOP THROUGH COMMENTS CHECKING LOCATIONS
	for($a = 0; $a < count($comments); $a++) {
		//if a is a multiple of 50 then wait 1 minute
		//TOO MANY REQUESTS IN 1 MINUTE GETS ME BLOCKED FROM USING GEOPLUGIN FOR 1 HOUR!!
		if($a % 50 == 0) {
			// sleep for 60 seconds
			sleep(60);
		}
		
		$comment = $comments[$a]; //THE ID's OF COMMENTS: 375, 357, 136, 132, 130, 73, 72, 66
		
		$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);
	
	$names = array_keys($locations_without_duplicates);
	$values = array_values($locations_without_duplicates);
	$resultz = "";
	
	for($b = 0; $b < count($names); $b++) {
		if($b != 0) {
			$resultz .= ", ";
		}
		$resultz .= $names[$b];
		$resultz .= " = ";
		$resultz .= $values[$b];
	}
	return $resultz;
}

Now I just have to figure out where I’m going to store this info so I don’t make the user wait 1-3 minutes for the shortcode to calculate this whenever they view the page I put it in.

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: