WordPress Plugin: Countdown Button
Oto kompletny plugin WordPress, który tworzy shortcode z przyciskiem odliczającym czas do wybranej daty, a po jej upływie wyświetla przycisk z linkiem. Czas jest pobierany z serwera, aby zapobiec manipulacjom po stronie klienta.
Instalacja
- Utwórz nowy folder w
/wp-content/plugins/ o nazwie countdown-button
- Utwórz plik
countdown-button.php w tym folderze i wklej poniższy kod:
<?php
/*
Plugin Name: Countdown Button
Description: Tworzy shortcode z przyciskiem odliczającym czas do wybranej daty, a po jej upływie wyświetla przycisk z linkiem.
Version: 1.0
Author: Twój Nick
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
class Countdown_Button_Plugin {
public function __construct() {
add_shortcode('countdown_button', array($this, 'countdown_button_shortcode'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_action('wp_ajax_get_server_time', array($this, 'get_server_time'));
add_action('wp_ajax_nopriv_get_server_time', array($this, 'get_server_time'));
}
public function enqueue_scripts() {
wp_enqueue_script('countdown-button', plugin_dir_url(__FILE__) . 'countdown-button.js', array('jquery'), '1.0', true);
wp_localize_script('countdown-button', 'countdownButtonAjax', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('countdown_button_nonce')
));
}
public function countdown_button_shortcode($atts) {
$atts = shortcode_atts(array(
'date' => '',
'time' => '00:00',
'button_text' => 'Kliknij tutaj',
'button_url' => '#',
'countdown_text' => 'Do końca pozostało:',
'button_class' => 'button',
'expired_text' => 'Czas minął!'
), $atts);
if (empty($atts['date'])) {
return '<p>Brak daty docelowej</p>';
}
$target_datetime = $this->parse_datetime($atts['date'], $atts['time']);
$current_time = current_time('timestamp');
$remaining_time = $target_datetime - $current_time;
$output = '<div class="countdown-button-container" data-target="' . esc_attr($target_datetime) . '">';
if ($remaining_time > 0) {
$output .= '<div class="countdown-text">' . esc_html($atts['countdown_text']) . '</div>';
$output .= '<div class="countdown-timer" data-remaining="' . esc_attr($remaining_time) . '">';
$output .= '<span class="days">00</span>d ';
$output .= '<span class="hours">00</span>h ';
$output .= '<span class="minutes">00</span>m ';
$output .= '<span class="seconds">00</span>s';
$output .= '</div>';
} else {
$output .= '<a href="' . esc_url($atts['button_url']) . '" class="' . esc_attr($atts['button_class']) . '">' . esc_html($atts['button_text']) . '</a>';
}
$output .= '</div>';
return $output;
}
private function parse_datetime($date, $time) {
$datetime_string = $date . ' ' . $time;
$datetime = DateTime::createFromFormat('Y-m-d H:i', $datetime_string);
if (!$datetime) {
// Jeśli format nie pasuje, spróbuj z innym formatem
$datetime = new DateTime($datetime_string);
}
return $datetime->getTimestamp();
}
public function get_server_time() {
check_ajax_referer('countdown_button_nonce', 'nonce');
$current_time = current_time('timestamp');
wp_send_json_success(array('server_time' => $current_time));
}
}
new Countdown_Button_Plugin();
- Utwórz plik
countdown-button.js w tym samym folderze i wklej poniższy kod:
jQuery(document).ready(function($) {
function updateCountdown() {
$('.countdown-button-container').each(function() {
var $container = $(this);
var targetTime = parseInt($container.data('target'));
var currentTime = Math.floor(new Date().getTime() / 1000);
// Pobierz czas z serwera co 5 minut, aby zsynchronizować
if (typeof lastServerSync === 'undefined' || (currentTime - lastServerSync) > 300) {
$.ajax({
url: countdownButtonAjax.ajaxurl,
type: 'POST',
data: {
action: 'get_server_time',
nonce: countdownButtonAjax.nonce
},
success: function(response) {
if (response.success) {
currentTime = response.data.server_time;
lastServerSync = currentTime;
}
},
async: false
});
}
var remainingTime = targetTime - currentTime;
if (remainingTime <= 0) {
// Czas minął - odśwież stronę
location.reload();
return;
}
var $timer = $container.find('.countdown-timer');
if ($timer.length) {
var seconds = remainingTime % 60;
var minutes = Math.floor(remainingTime / 60) % 60;
var hours = Math.floor(remainingTime / (60 * 60)) % 24;
var days = Math.floor(remainingTime / (60 * 60 * 24));
$timer.find('.days').text(this.pad(days, 2));
$timer.find('.hours').text(this.pad(hours, 2));
$timer.find('.minutes').text(this.pad(minutes, 2));
$timer.find('.seconds').text(this.pad(seconds, 2));
}
});
}
// Funkcja pomocnicza do formatowania liczb
function pad(num, size) {
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
// Aktualizuj co sekundę
updateCountdown();
setInterval(updateCountdown, 1000);
});
Jak używać
- Aktywuj plugin w panelu administracyjnym WordPress.
- Użyj shortcode w treści strony lub posta w następujący sposób:
[countdown_button date="2023-12-31" time="23:59" button_text="Kup teraz" button_url="https://twojlink.pl" countdown_text="Do końca promocji pozostało:" button_class="button primary"]
Parametry shortcode:
date - data docelowa w formacie YYYY-MM-DD (obowiązkowe)
time - czas docelowy w formacie HH:MM (opcjonalne, domyślnie 00:00)
button_text - tekst przycisku po upływie czasu (opcjonalne)
button_url - URL przycisku po upływie czasu (opcjonalne)
countdown_text - tekst przed odliczaniem (opcjonalne)
button_class - klasy CSS dla przycisku (opcjonalne)
expired_text - tekst wyświetlany po upływie czasu (opcjonalne)
Zabezpieczenia
- Czas jest pobierany z serwera co 5 minut, aby zsynchronizować odliczanie.
- Używany jest nonce do zabezpieczenia żądań AJAX.
- Dane są odpowiednio escapowane przy wyświetlaniu.
- Po upływie czasu strona się odświeża, aby zapobiec manipulacjom po stronie klienta.
Dostosowanie stylów
Aby dostosować wygląd przycisku i odliczania, możesz dodać własne style CSS do motywu lub użyć klasy button_class w shortcode, aby zastosować istniejące style motywu.