Skip to content

Instantly share code, notes, and snippets.

@timersys
Created August 26, 2020 20:56
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 timersys/c1bc470d6fb6995a3048e7c99fe49136 to your computer and use it in GitHub Desktop.
Save timersys/c1bc470d6fb6995a3048e7c99fe49136 to your computer and use it in GitHub Desktop.
Custom ZIP switcher for GeotargetingWP
<?php
/**
* Adds GeoTarget Widget
* @since 1.0.0
*/
class GeotS_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'geot_switcher', // Base ID
__( 'Geotarget Zip Switcher', 'geot' ), // Name
[ 'description' => __( 'Display a text field to let users change zip', 'geot' ), ] // Args
);
}
/**
* Front-end display of widget.
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*
* @see WP_Widget::widget()
*
*/
public function widget( $args, $instance ) {
// before and after widget arguments are defined by themes
echo $args['before_widget'];
// check if we have any previously selected item
$current = isset( $_COOKIE['geot_switcher'] ) ? (int) $_COOKIE['geot_switcher'] : '';
GeotSwitcher::form();
echo $args['after_widget'];
}
/**
* Back-end widget form.
*
* @param array $instance Previously saved values from database.
*
* @return string|void
* @see WP_Widget::form()
*
*/
public function form( $instance ) {
?>
<p>No settings available</p>
<?php
}
} // class Foo_Widget
.geot_zip_switcher_form {
display: flex;
padding: 10px 0;
align-items: center;
}
.geot_zip_container form{
display: flex;
}
.geot_zip_switcher{
margin: 0 10px;
max-width: 150px;
height: 43px;
}
.form.geot_zip_switcher_form h3{
margin-bottom: 0;
}
<?php
/*
Plugin Name: GeotargetingWP custom Zip Switcher
Plugin URI: https://geotargetingwp.com
Description: Custom dropdown widget for cities in GeotargetingWP
Author: Damian Logghe
Version: 1.0
*/
use GeotWP\Record\GeotRecord;
/**
* Class GeotSwitcher
* will create a dropdown widget for changing cities
*/
class GeotSwitcher {
/**
* GeotSwitcher constructor.
*/
public function __construct() {
// required files and assets
$this->includes();
add_action('wp_enqueue_scripts', [$this, 'assets']);
//register widget
add_action( 'widgets_init', [ $this, 'register_widget' ] );
// capture value
add_filter( 'geot/cancel_query', [ $this, 'set_custom_data' ] );
add_shortcode('geot-switcher', [ $this, 'geot_switcher_form']);
}
/**
* Main shortcode html
*/
public function geot_switcher_form(){
$current = isset( $_COOKIE['geot_switcher'] ) ? (int) $_COOKIE['geot_switcher'] : '';
self::form();
}
/**
* Files includes
*/
private function includes() {
require_once 'class-geot-dropdown-widget.php';
}
/**
* Enqueue assets
*/
public function assets() {
$v = current_user_can('manage_options') ? time() : '1.0.0.7';
wp_enqueue_script( 'geot-switcher', plugin_dir_url( __FILE__ ) . 'switcher.js', [ 'jquery', 'geot-js' ], $v, true );
wp_enqueue_style( 'geot-switcher', plugin_dir_url( __FILE__ ) . 'geot-switcher.css', [], $v);
}
/**
* Register widget into WP
*/
function register_widget() {
register_widget( 'GeotS_Widget' );
}
/**
* Check if switcher cookie exists and modify data
*/
function set_custom_data() {
// if no cookie continue with request to API
if ( empty( $_COOKIE['geot_switcher'] ) || ! $this->is_valid_zip($_COOKIE['geot_switcher']) ) {
return false;
}
$city = $_COOKIE['geot_switcher'];
// on this example we hardcoded the country and states but you can make it conditional based on your city
$data = [
'country' => 'United States',
'country_iso' => 'US',
'state' => 'Florida',
'state_iso' => 'FL',
'city' => 'Miami',
'zip' => (int) $_COOKIE['geot_switcher'],
];
// return formatted object to the plugin
return $this->formatter($data);
}
/**
* Check for valid zipz
*/
private function is_valid_zip($zipCode) {
return (preg_match('/^[0-9]{5}(-[0-9]{4})?$/', $zipCode)) ? true : false;
}
/**
* Format data to match GeotWP
*/
private function formatter( $data ) {
$state = new \stdClass;
$state->names = [ $data['state'] ];
$state->iso_code = $data['state_iso'];
$country = new \stdClass;
$country->names = [ $data['country'] ];
$country->iso_code = $data['country_iso'];
$continent = new \stdClass;
$continent->names = '';
$city = new \stdClass;
$city->names = [ $data['city'] ];
$city->zip = $data['zip'];
$geolocation = new \stdClass();
$geolocation->accuracy_radius = '';
$geolocation->longitude = '';
$geolocation->latitude = '';
$geolocation->time_zone = '';
return (object) [
'country' => $country,
'city' => $city,
'state' => $state,
'continent' => $continent,
'geolocation' => $geolocation,
];
}
/**
* The actual form
*/
public static function form() {
?>
<div class="geot_zip_container" >
<form method="GET" class="geot_zip_switcher_form">
<h3>Not shipping to <span class="geot_zip_code"><?= do_shortcode('[geot_zip]');?></span>?</h3>
<input type="text" class="geot_zip_switcher" name="geot_zip_switcher" placeholder="Zip code" value="">
<button type="submit" class="fusion-button button-flat fusion-button-default-size button-alt button-1 fusion-button-default-span fusion-button-default-type">Update</button>
</form>
</div>
<?php
}
}
new GeotSwitcher();
jQuery(function ($) {
$(document).ready(function () {
$(document).on('geotwp_ajax_success', function(e, data) {
if( GeotReadCookie('geot_switcher') == null && data.geo.length ) {
GeotCreateCookie('geot_switcher', data.geo.city.data.zip, 999);
}
$('.geot_zip_switcher').val(data.geo.city.data.zip);
});
// empty zip code when clicked ship to diff location
$(document).on('click','#ship-to-different-address-checkbox', function(){
$('#shipping_postcode').val('');
});
// if we have a switcher form
if ($('.geot_zip_switcher').length) {
// bind submit event
$('.geot_zip_switcher_form').on('submit', function(e){
e.preventDefault();
const $form = $(this),
$field = $form.find('.geot_zip_switcher');
GeotCreateCookie('geot_switcher', $field.val(), 999);
window.location.reload();
});
// if we already have a cookie populate form or ask for zip
if (GeotReadCookie('geot_switcher')) {
$('.geot_zip_code').val(GeotReadCookie('geot_switcher'))
}
}
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 1900; //time in ms (5 seconds)
//on keyup, start the countdown and check for checkout fields to see if match our cookie
$('#billing_postcode').keyup(function(){
clearTimeout(typingTimer);
if ($('#billing_postcode').val()) {
typingTimer = setTimeout(function(){
if( GeotReadCookie('geot_switcher') != $('#billing_postcode').val() ) {
GeotCreateCookie('geot_switcher', $('#billing_postcode').val(), 999);
PUM.open(5077);
}
}, doneTypingInterval);
}
});
// check form submission
$(document).on('click','.paypal-buttons', function(e){
e.preventDefault();
const $button = $(this);
// If shipping zip was added do nothing
if( $('#shipping_postcode').val() != '' ){
$button.click();
return;
} else {
// billing zip is shipping zip
if( GeotReadCookie('geot_switcher') != $('#billing_postcode').val() ) {
GeotCreateCookie('geot_switcher', $('#billing_postcode').val(), 999);
PUM.open(5077);
}
}
});
$('#shipping_postcode').keyup(function(){
clearTimeout(typingTimer);
if ($('#shipping_postcode').val()) {
typingTimer = setTimeout(function(){
if( GeotReadCookie('geot_switcher') != $('#shipping_postcode').val() ) {
GeotCreateCookie('geot_switcher', $('#shipping_postcode').val(), 999);
PUM.open(5077);
}
}, doneTypingInterval);
}
});
});
function GeotCreateCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function GeotReadCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment