Skip to content

Instantly share code, notes, and snippets.

@sfgarza
Created November 30, 2017 00:34
Show Gist options
  • Save sfgarza/0f56a0929cc68b96ce297d12e337501b to your computer and use it in GitHub Desktop.
Save sfgarza/0f56a0929cc68b96ce297d12e337501b to your computer and use it in GitHub Desktop.
Expire a particular WordPress users session everyday at midnight
<?php
$time = my_strtolocaltime( 'midnight' );
my_schedule_cron( 'my_destroy_sessions_cron', 'daily', $time );
add_action( 'my_destroy_sessions_cron', 'my_destroy_sessions' );
/**
* Destroy all sessions for guest user.
*
* @return void
*/
function my_destroy_sessions(){
// Grabs userdata by the username.
$user = get_user_by( 'login', 'guest' );
if( $user ) {
// get all sessions for user with ID $user_id
$sessions = WP_Session_Tokens::get_instance($user->ID);
// we have got the sessions, destroy them all!
$sessions->destroy_all();
}
}
/**
* Works much like strtotime() but uses the timezone setting in WordPress
* in order to convert it to localtime.
*
* @param string $str String to convert into time.
* @return int Unix time reflecting corresponding local time.
*/
function my_strtolocaltime( $str ){
if( '' !== get_option('timezone_string') ){
$tz = timezone_open( get_option( 'timezone_string' ) );
$now = new DateTime( "now", timezone_open ( '+0' ) );
$offset = timezone_offset_get( $tz , $now );
}
else{
$offset = get_option( 'gmt_offset' ) * HOUR_IN_SECONDS;
}
$time = strtotime($str) - $offset;
return $time;
}
/**
* Schedule cron Job.
*
* @static
* @param string $hook : Hook to use for cron event.
* @param string $recurrence : Cron recurrence period. i.e. daily, monthly, etc.
* @param int $time : Time to execute cron.
*/
function my_schedule_cron( $hook, $recurrence = null, $time = null ) {
// If reccurence and time not sent, then set defaults.
$recurrence = $recurrence ?? 'daily';
$time = $time ?? time();
// Schedule.
if ( ! wp_next_scheduled( $hook ) ) {
wp_schedule_event( $time, $recurrence , $hook );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment