Skip to content

Instantly share code, notes, and snippets.

@goldhat
Created May 25, 2017 16:27
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 goldhat/3e1da8eaaefa3b207abaf600e3c70614 to your computer and use it in GitHub Desktop.
Save goldhat/3e1da8eaaefa3b207abaf600e3c70614 to your computer and use it in GitHub Desktop.
gpls-time-period-handling
<?php
// time period handling segment
$time_period = $this->_args['time_period'];
$time_period_sql = false;
if( $time_period === false ) {
// no time period
} else if( intval( $time_period ) > 0 ) {
$time_period_sql = $wpdb->prepare( 'date_created BETWEEN DATE_SUB(utc_timestamp(), INTERVAL %d SECOND) AND utc_timestamp()', $this->_args['time_period'] );
} else {
$gmt_offset = get_option( 'gmt_offset' );
$date_func = $gmt_offset < 0 ? 'DATE_SUB' : 'DATE_ADD';
$hour_offset = abs( $gmt_offset );
$date_created_sql = sprintf( '%s( date_created, INTERVAL %d HOUR )', $date_func, $hour_offset );
$utc_timestamp_sql = sprintf( '%s( utc_timestamp(), INTERVAL %d HOUR )', $date_func, $hour_offset );
switch( $time_period ) {
case 'per_day':
case 'day':
$time_period_sql = "DATE( $date_created_sql ) = DATE( $utc_timestamp_sql )";
break;
case 'per_week':
case 'week':
$time_period_sql = "WEEK( $date_created_sql ) = WEEK( $utc_timestamp_sql )";
$time_period_sql .= "AND YEAR( $date_created_sql ) = YEAR( $utc_timestamp_sql )";
break;
case 'per_month':
case 'month':
$time_period_sql = "MONTH( $date_created_sql ) = MONTH( $utc_timestamp_sql )";
$time_period_sql .= "AND YEAR( $date_created_sql ) = YEAR( $utc_timestamp_sql )";
break;
case 'per_year':
case 'year':
$time_period_sql = "YEAR( $date_created_sql ) = YEAR( $utc_timestamp_sql )";
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment