首页 WordPress教程 重磅:如何给单页添加验证邮箱的按钮,搜集邮箱

重磅:如何给单页添加验证邮箱的按钮,搜集邮箱

作者 WP导师

HTML 部分

//首先在页面上添加一个按钮,点击弹出验证邮箱和弹出验证码: 
<p>产品图纸:<a href="javascript:void(0)" type="button" id="verifyEmailButton">点击进行下载图纸</a></p>

//验证邮箱的form, 写在页面最底部 
<!-- The popup form -->
<div id="emailPopup" class="popup">
    <div class="popup-content">
        <span class="close">&times;</span>
        <form id="emailForm">
            <label for="email">Enter your email:</label>
            <input type="email" id="email" name="email" required>
            <button type="button" id="sendCodeButton">Send Verification Code</button>
        </form>
        <form id="codeForm" style="display:none;">
            <label for="verificationCode">Enter verification code:</label>
            <input type="text" id="verificationCode" name="verificationCode" required>
            <button type="button" id="verifyCodeButton">Verify Code</button>
        </form>
    </div>
</div>

//添加合适的css来改变弹出form的样式
/*
popup form
 */

.popup {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0,0.4);
    padding-top: 60px;
}

.popup-content {
    background-color: #fefefe;
    margin: 5% auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
    max-width: 500px;
}

.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

//添加js进行控制,首先点击弹出form框
document.addEventListener('DOMContentLoaded', function() {
    var popup = document.getElementById('emailPopup');
    var btn = document.getElementById('verifyEmailButton');
    var span = document.getElementsByClassName('close')[0];
    var emailForm = document.getElementById('emailForm');
    var codeForm = document.getElementById('codeForm');

    btn.onclick = function() {
//点击弹出form框
        popup.style.display = 'block';

    }

    span.onclick = function() {
//点击关闭form框
        popup.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target == popup) {
            popup.style.display = 'none';
        }
    }

    document.getElementById('sendCodeButton').addEventListener('click', function() {
        var email = document.getElementById('email').value;
        if (email) {
      //如果email存在,发送wp ajax 到后端,来执行发送邮箱验证码
     // ajax_object.ajax_url 必须通过wp_localize_script来进行本地化传递
            fetch(ajax_object.ajax_url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=send_verification_code&email=' + encodeURIComponent(email),
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                //如果从后端传递的json返回正确
                    emailForm.style.display = 'none';
                    codeForm.style.display = 'block';
                    codeForm.dataset.email = email; // 存储email的信息到data属性里好在下面验证阶段进行使用
                } else {
                    alert('Failed to send verification code. Please try again.');
                }
            });
        }
    });

    document.getElementById('verifyCodeButton').addEventListener('click', function() {
        var code = document.getElementById('verificationCode').value;
        var email = document.getElementById('codeForm').dataset.email; // 获得当前验证的email
        if (code && email) {
//如果都存在验证码和邮箱,注意body传递很多信息到 后端的post 请求
          fetch(ajax_object.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'action=verify_code&code=' + encodeURIComponent(code) + '&email=' + encodeURIComponent(email), 
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                

                document.getElementById('emailPopup').style.display = 'none';
                document.getElementById('verifyEmailButton').innerText = 'Verified!';
                // 这里来显示你要显示的内容或者更改的内容
                //document.getElementById('extraContent').style.display = 'block';
            } else {
                alert('Incorrect verification code. Please try again.');
            }
        });

        }
        
    });
});

//PHP部分 
//首先创建存储验证email的table 
function create_verified_emails_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'verified_emails';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        email varchar(255) NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

add_action('after_switch_theme', 'create_verified_emails_table');

//执行第一个ajax,也就是发送随机验证码到邮件,注意如何生成随机验证码的用法
function send_verification_code() {
    if (isset($_POST['email'])) {
        $email = sanitize_email($_POST['email']);
        if (!is_email($email)) {
            wp_send_json_error(array('message' => 'Invalid email address.'));
        }

        $verification_code = wp_rand(100000, 999999);
       //设置缓存,将验证码保存到缓存
      //注意,失效时间这里是300秒, MINUTE_IN_SECONDS 是 60秒
        set_transient('email_verification_code_' . $email, $verification_code, 5 * MINUTE_IN_SECONDS);

        $subject = 'Your Verification Code';
        $message = 'Your verification code is ' . $verification_code;
        $headers = array('Content-Type: text/html; charset=UTF-8');

        if (wp_mail($email, $subject, $message, $headers)) {
            wp_send_json_success();
        } else {
            wp_send_json_error(array('message' => 'Failed to send email.'));
        }
    } else {
        wp_send_json_error(array('message' => 'No email provided.'));
    }
}
add_action('wp_ajax_send_verification_code', 'send_verification_code');
add_action('wp_ajax_nopriv_send_verification_code', 'send_verification_code');

//第二个ajax, 进行验证码的验证,如果post传递过来的验证码和保存的验证码相符,将进行验证的邮箱保存到数据库
function verify_code() {
    if (isset($_POST['code']) && isset($_POST['email'])) {
        $code = sanitize_text_field($_POST['code']);
        $email = sanitize_email($_POST['email']);
        $saved_code = get_transient('email_verification_code_' . $email); //提取缓存进行验证

        if ($code == $saved_code) {
            delete_transient('email_verification_code_' . $email);

            global $wpdb;
            $table_name = $wpdb->prefix . 'verified_emails';
            $wpdb->insert($table_name, array('email' => $email));
            wp_send_json_success();
        } else {
            wp_send_json_error(array('message' => 'Incorrect verification code.'));
        }
    } else {
        wp_send_json_error(array('message' => 'Invalid request.'));
    }
}
add_action('wp_ajax_verify_code', 'verify_code');
add_action('wp_ajax_nopriv_verify_code', 'verify_code');

//添加后台管理菜单 来展示存储的邮箱列表
function add_verified_emails_menu() {
    add_menu_page(
        'Verified Emails',
        'Verified Emails',
        'manage_options',
        'verified-emails',
        'display_verified_emails_page',
        'dashicons-email-alt',
        20
    );

}
add_action('admin_menu', 'add_verified_emails_menu');

function display_verified_emails_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'verified_emails';
    $emails = $wpdb->get_results("SELECT * FROM $table_name");

    echo '<div class="wrap">';
    echo '<h1>Verified Emails</h1>';
    echo '<table class="wp-list-table widefat fixed striped">';
    echo '<thead><tr><th>ID</th><th>Email</th></tr></thead>';
    echo '<tbody>';

    if ($emails) {
        foreach ($emails as $email) {
            echo '<tr>';
            echo '<td>' . esc_html($email->id) . '</td>';
            echo '<td>' . esc_html($email->email) . '</td>';
            echo '</tr>';
        }
    } else {
        echo '<tr><td colspan="2">No verified emails found.</td></tr>';
    }

    echo '</tbody></table>';
    echo '</div>';
}

您可能还喜欢

发表评论