Skip to content

Instantly share code, notes, and snippets.

@AchalJ
Created March 25, 2022 16:43
Show Gist options
  • Select an option

  • Save AchalJ/eb8d5c32ea4a1411fff7d9829b2656d1 to your computer and use it in GitHub Desktop.

Select an option

Save AchalJ/eb8d5c32ea4a1411fff7d9829b2656d1 to your computer and use it in GitHub Desktop.
Auto-reset Countdown Timer shortcode
/**
* How to use: [my_custom_timer id="my-timer" time="300" placeholder="00:00"]
*/
add_shortcode( 'my_custom_timer', function( $attrs ) {
// id attribute for the timer HTML.
$id = isset( $attrs['id'] ) && ! empty( $attrs['id'] ) ? $attrs['id'] : 'my-timer';
// set the time to start countdown (in seconds).
$time = isset( $attrs['time'] ) && ! empty( $attrs['time'] ) ? intval( $attrs['time'] ) : 120;
// default placeholder to appear on load
$placeholder = isset( $attrs['placeholder'] ) ? $attrs['placeholder'] : '';
ob_start();
?>
<div class="my-custom-timer" id="<?php esc_attr_e( $id ); ?>" data-time="<?php echo $time; ?>"><?php echo $placeholder; ?></div>
<script>
;(function($) {
var init = function() {
var timeleft = <?php echo $time; ?>, minutes, seconds;
var timer = setInterval(function() {
if(timeleft <= 0){
clearInterval(timer);
init();
}
minutes = (timeleft / 60) | 0;
seconds = (timeleft % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$("#<?php esc_attr_e( $id ); ?>").html( minutes + ":" + seconds );
timeleft -= 1;
}, 1000);
};
init();
})(jQuery);
</script>
<?php
return ob_get_clean();
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment