# Chia sẽ code plugin tạo thời gian chờ tải cho nút download

## Chia sẽ code plugin tạo thời gian chờ tải cho nút download

[![](https://drive.inet.vn/uploads/hobv@inet.vn/Hosting/dang-ky-hosting/file-1538983079768_google-ads\(728x90\).png)](https://inet.vn/hosting/web-hosting?aff=449228)*Nhập mã **webantamgiam30%** được giảm 30% khi đăng ký hosting hay vps tại* [***inet.vn***](https://inet.vn/hosting/web-hosting?aff=449228)

&#x20;Mục lục

1. [1 Ưu điểm](https://webantam.com/code-tao-thoi-gian-cho-tai-cho-nut-download/?fbclid=IwY2xjawE1WbJleHRuA2FlbQIxMAABHXSyTYiNXzqiriXcxmZcNEuAkk7mAKLB3e7VpttjEbnrS57y7G8NkdeDJQ_aem_kea22Nt8GC8jHDxyc2WCAw#section-1)
2. [2 Video hướng dẫn](https://webantam.com/code-tao-thoi-gian-cho-tai-cho-nut-download/?fbclid=IwY2xjawE1WbJleHRuA2FlbQIxMAABHXSyTYiNXzqiriXcxmZcNEuAkk7mAKLB3e7VpttjEbnrS57y7G8NkdeDJQ_aem_kea22Nt8GC8jHDxyc2WCAw#section-2)
3. [3 Chèn code vào funtion.php hoặc cài plugin do Web An Tâm phát triển](https://webantam.com/code-tao-thoi-gian-cho-tai-cho-nut-download/?fbclid=IwY2xjawE1WbJleHRuA2FlbQIxMAABHXSyTYiNXzqiriXcxmZcNEuAkk7mAKLB3e7VpttjEbnrS57y7G8NkdeDJQ_aem_kea22Nt8GC8jHDxyc2WCAw#section-3)
4. [4 Cách sử dụng](https://webantam.com/code-tao-thoi-gian-cho-tai-cho-nut-download/?fbclid=IwY2xjawE1WbJleHRuA2FlbQIxMAABHXSyTYiNXzqiriXcxmZcNEuAkk7mAKLB3e7VpttjEbnrS57y7G8NkdeDJQ_aem_kea22Nt8GC8jHDxyc2WCAw#section-4)
5. [5 Kết bài](https://webantam.com/code-tao-thoi-gian-cho-tai-cho-nut-download/?fbclid=IwY2xjawE1WbJleHRuA2FlbQIxMAABHXSyTYiNXzqiriXcxmZcNEuAkk7mAKLB3e7VpttjEbnrS57y7G8NkdeDJQ_aem_kea22Nt8GC8jHDxyc2WCAw#section-5)

Mở đầu viết gì nhỉ, thôi thì hôm nay mình sẽ chia sẽ code tạo thời gian chờ tải cho nút download, để các bạn có thể tham khảo xem code, sửa code, mình viết khá là clean… có plugin cho bạn cài vào nếu bạn không rành code

<figure><img src="https://webantam.com/wp-content/uploads/2024/01/tao-thoi-gian-cho-tai-cho-nut-download.png" alt="Tạo thời gian chờ tải cho nút download" height="788" width="940"><figcaption><p>Tạo thời gian chờ tải cho nút download</p></figcaption></figure>

### Ưu điểm <a href="#section-1" id="section-1"></a>

* Tăng thời gian onsite cho website tốt cho seo
* Phát hiện nếu người dùng chuyển sang cửa sổ khác sẽ ngừng nhảy giây
* Tự động nhảy sang tab mới của link download khi hết số giây chờ

### Video hướng dẫn <a href="#section-2" id="section-2"></a>

### Chèn code vào funtion.php hoặc cài plugin do Web An Tâm phát triển <a href="#section-3" id="section-3"></a>

* **Cách 1: chèn code vào file funtion.php**

các bạn chèn code sau vào **file funtion.php** của **child theme** và xóa cache đi nhé

```php
// code tao thoi gian cho tai cho nut download webantam.com

// Thêm shortcode để gọi button download
function download_button_shortcode($atts) {
    $atts = shortcode_atts(
        array(
            'href' => '', // Không cần giá trị mặc định
            'text' => 'Tải ngay', // Giá trị mặc định của nội dung button
        ),
        $atts,
        'download_button'
    );

    ob_start();
    ?>
    
    <style>
        .download-btn button {
            border-radius: 99px;
            padding: 5px 30px 5px 30px;
            background: #1e7dff;
            color: white;
            border: none;
            cursor: pointer;
        }

        .download-btn button:hover {
            background: linear-gradient(270.5deg, #f79922 -.62%, #ff7a00 99.14%);
            border: 1px solid #3658d1;
        }
    </style>
    
    <div class="download-btn" style="text-align: center;">
        <button data-download-href="<?php echo esc_url($atts['href']); ?>"><?php echo esc_html($atts['text']); ?></button>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var countdownTimer;
            var timeLeft = 30; // Thời gian chờ trong giây
            var isWaiting = false; // Biến kiểm tra xem có đang chờ không
            var isActiveTab = true; // Biến kiểm tra xem tab có đang active không
            var hasRedirected = false; // Biến kiểm tra xem đã chuyển hướng chưa
            var hasCountdownStarted = false; // Biến kiểm tra xem đã bắt đầu đếm ngược hay chưa
            var originalButtonText = "<?php echo esc_html($atts['text']); ?>";
            var isDownloadButtonVisible = true; // Biến kiểm tra xem nút "Download" có hiển thị không

            // Function to start the countdown
            function startCountdown(button) {
                // Start the countdown
                countdownTimer = setInterval(function () {
                    timeLeft--;

                    // Display countdown on the button
                    button.innerHTML = "Bạn vui lòng chờ " + timeLeft + " giây";

                    if (timeLeft <= 0) {
                        clearInterval(countdownTimer);

                        // Perform the download here
                        var download_href = button.getAttribute('data-download-href');
                        if (isActiveTab && !hasRedirected) {
                            window.open(download_href, '_blank');
                            hasRedirected = true; // Đặt lại biến đã chuyển hướng
                        } else if (!hasRedirected) {
                            // Open link in a new tab/window
                            var newWindow = window.open(download_href, '_blank');
                            if (newWindow) {
                                newWindow.focus();
                                hasRedirected = true; // Đặt lại biến đã chuyển hướng
                            } else {
                                // Handle the case when the window couldn't be opened
                                alert('Popup blocked! Please allow popups to download.');
                            }
                        }

                        // You can update the UI as needed
                        button.innerHTML = originalButtonText; // Hiển thị lại nút download
                        isDownloadButtonVisible = true; // Đặt lại biến đã hiển thị nút download
                        isWaiting = false; // Reset biến khi đã hoàn thành quá trình chờ
                        timeLeft = 30; // Reset giá trị timeLeft
                        hasCountdownStarted = false; // Đặt lại biến đã bắt đầu đếm ngược
                    }
                }, 1000);
            }

            // Function to pause the countdown
            function pauseCountdown() {
                clearInterval(countdownTimer);
            }

            // Function to resume the countdown
            function resumeCountdown(button) {
                startCountdown(button);
                hasCountdownStarted = true; // Đặt biến đã bắt đầu đếm ngược
            }

            // Event listener for clicks on elements with class 'download-btn'
            var downloadButtons = document.querySelectorAll('.download-btn button');
            for (var i = 0; i < downloadButtons.length; i++) {
                downloadButtons[i].addEventListener('click', function (event) {
                    var button = event.target.closest('.download-btn button');
                    if (button && !isWaiting && !hasCountdownStarted && isDownloadButtonVisible) {
                        event.preventDefault(); // Ngăn chặn chuyển hướng mặc định của nút
                        isWaiting = true;
                        resumeCountdown(button);
                        isDownloadButtonVisible = false; // Đặt biến ẩn nút download
                        hasRedirected = false; // Reset biến đã chuyển hướng
                    }
                });
            }

            // Sự kiện khi thay đổi trạng thái của tab
            document.addEventListener('visibilitychange', function () {
                isActiveTab = !document.hidden;

                if (isActiveTab && countdownTimer && hasCountdownStarted) {
                    resumeCountdown(document.querySelector(".download-btn button"));
                } else {
                    pauseCountdown();
                }
            });

            // Initial setup to avoid automatic countdown when returning to the main tab
            if (!isActiveTab) {
                pauseCountdown();
            }
        });
    </script>
    <?php
    $output = ob_get_clean();
    return $output;
}
add_shortcode('download_button', 'download_button_shortcode');

// code tao thoi gian cho tai cho nut download webantam.com end
```

|   | // code tao thoi gian cho tai cho nut download webantam.com                                                                |
| - | -------------------------------------------------------------------------------------------------------------------------- |
|   |                                                                                                                            |
|   | // Thêm shortcode để gọi button download                                                                                   |
|   | function download\_button\_shortcode($atts) {                                                                              |
|   | $atts = shortcode\_atts(                                                                                                   |
|   | array(                                                                                                                     |
|   | 'href' => '', // Không cần giá trị mặc định                                                                                |
|   | 'text' => 'Tải ngay', // Giá trị mặc định của nội dung button                                                              |
|   | ),                                                                                                                         |
|   | $atts,                                                                                                                     |
|   | 'download\_button'                                                                                                         |
|   | );                                                                                                                         |
|   |                                                                                                                            |
|   | ob\_start();                                                                                                               |
|   | ?>                                                                                                                         |
|   |                                                                                                                            |
|   | \<style>                                                                                                                   |
|   | .download-btn button {                                                                                                     |
|   | border-radius: 99px;                                                                                                       |
|   | padding: 5px 30px 5px 30px;                                                                                                |
|   | background: #1e7dff;                                                                                                       |
|   | color: white;                                                                                                              |
|   | border: none;                                                                                                              |
|   | cursor: pointer;                                                                                                           |
|   | }                                                                                                                          |
|   |                                                                                                                            |
|   | .download-btn button:hover {                                                                                               |
|   | background: linear-gradient(270.5deg, #f79922 -.62%, #ff7a00 99.14%);                                                      |
|   | border: 1px solid #3658d1;                                                                                                 |
|   | }                                                                                                                          |
|   | \</style>                                                                                                                  |
|   |                                                                                                                            |
|   | \<div class="download-btn" style="text-align: center;">                                                                    |
|   | \<button data-download-href="\<?php echo esc\_url($atts\['href']); ?>">\<?php echo esc\_html($atts\['text']); ?>\</button> |
|   | \</div>                                                                                                                    |
|   | \<script>                                                                                                                  |
|   | document.addEventListener('DOMContentLoaded', function () {                                                                |
|   | var countdownTimer;                                                                                                        |
|   | var timeLeft = 30; // Thời gian chờ trong giây                                                                             |
|   | var isWaiting = false; // Biến kiểm tra xem có đang chờ không                                                              |
|   | var isActiveTab = true; // Biến kiểm tra xem tab có đang active không                                                      |
|   | var hasRedirected = false; // Biến kiểm tra xem đã chuyển hướng chưa                                                       |
|   | var hasCountdownStarted = false; // Biến kiểm tra xem đã bắt đầu đếm ngược hay chưa                                        |
|   | var originalButtonText = "\<?php echo esc\_html($atts\['text']); ?>";                                                      |
|   | var isDownloadButtonVisible = true; // Biến kiểm tra xem nút "Download" có hiển thị không                                  |
|   |                                                                                                                            |
|   | // Function to start the countdown                                                                                         |
|   | function startCountdown(button) {                                                                                          |
|   | // Start the countdown                                                                                                     |
|   | countdownTimer = setInterval(function () {                                                                                 |
|   | timeLeft--;                                                                                                                |
|   |                                                                                                                            |
|   | // Display countdown on the button                                                                                         |
|   | button.innerHTML = "Bạn vui lòng chờ " + timeLeft + " giây";                                                               |
|   |                                                                                                                            |
|   | if (timeLeft <= 0) {                                                                                                       |
|   | clearInterval(countdownTimer);                                                                                             |
|   |                                                                                                                            |
|   | // Perform the download here                                                                                               |
|   | var download\_href = button.getAttribute('data-download-href');                                                            |
|   | if (isActiveTab && !hasRedirected) {                                                                                       |
|   | window\.open(download\_href, '\_blank');                                                                                   |
|   | hasRedirected = true; // Đặt lại biến đã chuyển hướng                                                                      |
|   | } else if (!hasRedirected) {                                                                                               |
|   | // Open link in a new tab/window                                                                                           |
|   | var newWindow = window\.open(download\_href, '\_blank');                                                                   |
|   | if (newWindow) {                                                                                                           |
|   | newWindow\.focus();                                                                                                        |
|   | hasRedirected = true; // Đặt lại biến đã chuyển hướng                                                                      |
|   | } else {                                                                                                                   |
|   | // Handle the case when the window couldn't be opened                                                                      |
|   | alert('Popup blocked! Please allow popups to download.');                                                                  |
|   | }                                                                                                                          |
|   | }                                                                                                                          |
|   |                                                                                                                            |
|   | // You can update the UI as needed                                                                                         |
|   | button.innerHTML = originalButtonText; // Hiển thị lại nút download                                                        |
|   | isDownloadButtonVisible = true; // Đặt lại biến đã hiển thị nút download                                                   |
|   | isWaiting = false; // Reset biến khi đã hoàn thành quá trình chờ                                                           |
|   | timeLeft = 30; // Reset giá trị timeLeft                                                                                   |
|   | hasCountdownStarted = false; // Đặt lại biến đã bắt đầu đếm ngược                                                          |
|   | }                                                                                                                          |
|   | }, 1000);                                                                                                                  |
|   | }                                                                                                                          |
|   |                                                                                                                            |
|   | // Function to pause the countdown                                                                                         |
|   | function pauseCountdown() {                                                                                                |
|   | clearInterval(countdownTimer);                                                                                             |
|   | }                                                                                                                          |
|   |                                                                                                                            |
|   | // Function to resume the countdown                                                                                        |
|   | function resumeCountdown(button) {                                                                                         |
|   | startCountdown(button);                                                                                                    |
|   | hasCountdownStarted = true; // Đặt biến đã bắt đầu đếm ngược                                                               |
|   | }                                                                                                                          |
|   |                                                                                                                            |
|   | // Event listener for clicks on elements with class 'download-btn'                                                         |
|   | var downloadButtons = document.querySelectorAll('.download-btn button');                                                   |
|   | for (var i = 0; i < downloadButtons.length; i++) {                                                                         |
|   | downloadButtons\[i].addEventListener('click', function (event) {                                                           |
|   | var button = event.target.closest('.download-btn button');                                                                 |
|   | if (button && !isWaiting && !hasCountdownStarted && isDownloadButtonVisible) {                                             |
|   | event.preventDefault(); // Ngăn chặn chuyển hướng mặc định của nút                                                         |
|   | isWaiting = true;                                                                                                          |
|   | resumeCountdown(button);                                                                                                   |
|   | isDownloadButtonVisible = false; // Đặt biến ẩn nút download                                                               |
|   | hasRedirected = false; // Reset biến đã chuyển hướng                                                                       |
|   | }                                                                                                                          |
|   | });                                                                                                                        |
|   | }                                                                                                                          |
|   |                                                                                                                            |
|   | // Sự kiện khi thay đổi trạng thái của tab                                                                                 |
|   | document.addEventListener('visibilitychange', function () {                                                                |
|   | isActiveTab = !document.hidden;                                                                                            |
|   |                                                                                                                            |
|   | if (isActiveTab && countdownTimer && hasCountdownStarted) {                                                                |
|   | resumeCountdown(document.querySelector(".download-btn button"));                                                           |
|   | } else {                                                                                                                   |
|   | pauseCountdown();                                                                                                          |
|   | }                                                                                                                          |
|   | });                                                                                                                        |
|   |                                                                                                                            |
|   | // Initial setup to avoid automatic countdown when returning to the main tab                                               |
|   | if (!isActiveTab) {                                                                                                        |
|   | pauseCountdown();                                                                                                          |
|   | }                                                                                                                          |
|   | });                                                                                                                        |
|   | \</script>                                                                                                                 |
|   | \<?php                                                                                                                     |
|   | $output = ob\_get\_clean();                                                                                                |
|   | return $output;                                                                                                            |
|   | }                                                                                                                          |
|   | add\_shortcode('download\_button', 'download\_button\_shortcode');                                                         |
|   |                                                                                                                            |
|   | // code tao thoi gian cho tai cho nut download webantam.com end                                                            |

[view raw](https://gist.github.com/webantam43/38df0d6c017876017aa3df5d85d2a1a4/raw/1826a04067f2f9286915aece0d89fd10a308102b/code%20tao%20thoi%20gian%20cho%20tai%20cho%20nut%20download%20webantam.com)[code tao thoi gian cho tai cho nut download webantam.com ](https://gist.github.com/webantam43/38df0d6c017876017aa3df5d85d2a1a4#file-code-tao-thoi-gian-cho-tai-cho-nut-download-webantam-com)hosted with ❤ by [GitHub](https://github.com/)

* **Cách 2: Cài plugin do Web An Tâm phát triển**

TẢI NGAY

Nếu cài plugin thì bạn hãy sử dụng key **13726D05-E1BC3A91-21CF44D5-6DEF4E4D** để kích hoạt mới sử dụng được plugin nhé ( xem hình minh họa bên dưới )

{% file src="<https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FboqCwEAmo8zHWYhDCYSf%2FWaiting_time_Webantam_v1_3_licensed.zip?alt=media&token=5f804422-141c-4c2a-854d-f4eddc1f4589>" %}

<figure><img src="https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M1E4Gk2ppVKb4olmnun%2Fuploads%2FD0k2BjwcnED0ECskT974%2Fimage.png?alt=media&#x26;token=4102442a-1b2e-4aaa-89a1-3dc008d3a092" alt=""><figcaption></figcaption></figure>
