Skip to content

Instantly share code, notes, and snippets.

@webdados
Last active November 22, 2018 20:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save webdados/57682c9f7e4dad416f1ab0ec4b7476d5 to your computer and use it in GitHub Desktop.
Save webdados/57682c9f7e4dad416f1ab0ec4b7476d5 to your computer and use it in GitHub Desktop.
A simple Javascript timer for Magic Coupon
<?php
//Add new placeholder - Place {timer} on the message
add_filter( 'magic_coupon_html_message_replace_tags', function( $replace_tags ) {
$replace_tags['timer'] = '[my_magic_coupon_timer expire="{cookie_expire_timestamp}"]';
return $replace_tags;
} );
//The shortcode
add_shortcode( 'my_magic_coupon_timer', function( $atts ) {
ob_start();
$rand = rand( 0,99999 );
$time = intval( $atts['expire'] ) - time();
?>
<script type="text/javascript">
function startTimer<?php echo $rand; ?>(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var display = document.querySelector('#time<?php echo $rand; ?>');
startTimer<?php echo $rand; ?>(<?php echo $time; ?>, display);
};
</script>
<span id="time<?php echo $rand; ?>"><?php
$minutes = intval( $time / 60 );
$seconds = $time - ( $minutes * 60 );
echo ( $minutes >= 10 ? $minutes : '0'.$minutes ).':'.( $seconds >= 10 ? $seconds : '0'.$seconds );
?></span>
<?php
return ob_get_clean();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment