Skip to content

Instantly share code, notes, and snippets.

@SadikBhimani
Created July 19, 2017 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SadikBhimani/3efd92dbb503d98c0253e6fe1556d8e1 to your computer and use it in GitHub Desktop.
Save SadikBhimani/3efd92dbb503d98c0253e6fe1556d8e1 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Import Venues WP CLI command
Plugin URI: http://wordpress.org/plugins/hello-dolly/
Description: Adds `wp eo venue import <path-to-file>` command.
Author: Stephen Harris
Version: 0.1
*/
// Exit if accessed directly
if (!defined('ABSPATH'))
{
exit;
}
if (!defined('WP_CLI'))
{
return;
}
class EO_Venue_CLI_Command extends \WP_CLI_Command
{
/**
* The venue properties in the order they appear in the CSV file:
*/
protected $column_map = array(
'name',
'address',
'description',
'city',
'state',
'country',
'latitude',
'longtitude',
);
/**
* Import venues from a CSV file.
*
* ## OPTIONS
*
* [<file>]
* : Import venues from thie CSV file
*
* [--dry-run]
* : Parse the CSV file but do not create any venues
*
* [--skip-first-row]
* : Do not use the first row to import venues
*
* [--delimiter=<value>]
* : One of , ';' or tab
*
* ## EXAMPLES
*
* wp eo venue import ~/venues.csv --skip-first-row --dry-run
*
* wp eo venue import ~/venues.csv --delimiter=; --dry-run
*
* wp eo venue import ~/venues.csv --delimiter=tab
*/
public function import($args, $assoc_args)
{
//TODO tab/semicolon delimiter!
$assoc_args = array_merge(array(
'delimiter' => ',',
'dry-run' => 0,
'skip-first-row' => false,
), $assoc_args);
if (strtolower($assoc_args['delimiter']) === 'tab')
{
$assoc_args['delimiter'] = "\t";
}
if (strtolower($assoc_args['delimiter']) === 'semicolon')
{
$assoc_args['delimiter'] = ";";
}
if (strtolower($assoc_args['delimiter']) === 'comma')
{
$assoc_args['delimiter'] = ",";
}
if (!in_array($assoc_args['delimiter'], array("\t", ",", ";")))
{
WP_CLI::error("Unexpected delimeter. Expected --delimiter=';', --delimiter=, or --delimiter=tab ");
}
$file = array_shift($args);
if (!is_readable($file))
{
WP_CLI::error("Can't read '$file' file.");
}
$row = 0;
$errors = 0;
$imported = 0;
if (( $handle = fopen($file, 'r') ) !== FALSE)
{
while (( $line = fgetcsv($handle, 1000, $assoc_args['delimiter']) ) !== FALSE)
{
$row++;
if ($assoc_args['skip-first-row'])
{
$assoc_args['skip-first-row'] = false;
continue;
}
if (array_filter($line, 'trim'))
{
WP_CLI::log("Importing venue from row $row...");
$keys = array_slice($this->column_map, 0, count($line));
$venue = array_combine($keys, $line);
if ($assoc_args['dry-run'])
{
$args = array(
'format' => 'table',
'fields' => $keys
);
$formatter = new \WP_CLI\Formatter($args);
$formatter->display_item($venue);
$imported++;
}
else
{
$latLong = $this->getLatLong($venue['address']);
if(isset($latLong['latitude']) && isset($latLong['longtitude']))
{
$venue['latitude'] = $latLong['latitude'];
$venue['longtitude'] = $latLong['longtitude'];
}
$return = eo_insert_venue($venue['name'], $venue);
if (is_wp_error($return))
{
WP_CLI::warning($return);
$errors++;
}
else
{
WP_CLI::success(sprintf("Venue \"%s\" created - %d", $venue['name'], $return['term_id']));
$imported++;
}
}
}
else
{
WP_CLI::warning("Skipping row $row, as it is empty.");
}
}
fclose($handle);
}
if ($imported == 0 || $errors > 0)
{
WP_CLI::warning("Imported $imported venues. $errors venues not imported.");
}
elseif ($assoc_args['dry-run'])
{
WP_CLI::success("Dry run. Found {$imported} venues.");
}
else
{
WP_CLI::success("Imported $imported venues.");
}
}
protected function getLatLong($address)
{
if (!empty($address))
{
//Our Data has too many stray # and , symbols
//You can comment out the below the two lines
$address = str_replace('#', '', $address);
$address = str_replace(',', '', $address);
//Formatted address
$formattedAddr = str_replace(' ', '+', $address);
$key = '<YOUR GOOGLE MAPS API KEY>';
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $formattedAddr . '&sensor=false&key=' . $key;
//Send request and receive json data by address
$geocodeFromAddr = $this->url_get_contents($url);
$output = json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$data['latitude'] = $output->results[0]->geometry->location->lat;
$data['longtitude'] = $output->results[0]->geometry->location->lng;
//Return latitude and longitude of the given address
if (!empty($data))
{
return $data;
}
else
{
return false;
}
}
else
{
return false;
}
}
protected function url_get_contents($url)
{
if (!function_exists('curl_init'))
{
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
WP_CLI::add_command('eo venue', 'EO_Venue_CLI_Command');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment