请求为WordPress仪表盘页面开发邮件发送表单
如何在WordPress仪表盘添加邮件发送表单
1. 注册仪表盘菜单项
在主题的functions.php文件或自定义插件中添加以下代码,创建专属的仪表盘工具页面:
function add_mail_sender_menu() { add_menu_page( '邮件发送工具', // 页面标题 '邮件发送', // 侧边栏菜单名称 'manage_options', // 访问权限(仅管理员可操作) 'mail-sender', // 页面唯一标识slug 'render_mail_sender_page', // 页面渲染回调函数 'dashicons-email', // 菜单图标 6 // 菜单排序位置 ); } add_action('admin_menu', 'add_mail_sender_menu');
2. 渲染邮件发送表单
实现页面渲染回调函数,输出带安全验证的表单:
function render_mail_sender_page() { // 权限校验 if (!current_user_can('manage_options')) { wp_die('你没有权限访问此页面'); } // 显示提交结果提示 if (isset($_GET['mail_status'])) { $status = $_GET['mail_status']; if ($status === 'success') { echo '<div class="notice notice-success is-dismissible"><p>邮件发送成功!</p></div>'; } elseif ($status === 'error') { echo '<div class="notice notice-error is-dismissible"><p>邮件发送失败,请检查收件人邮箱和内容是否合法!</p></div>'; } } ?> <div class="wrap"> <h1><?php echo esc_html(get_admin_page_title()); ?></h1> <form method="post" action="<?php echo admin_url('admin-post.php'); ?>"> <?php // 添加安全验证nonce字段 wp_nonce_field('mail_sender_action', 'mail_sender_nonce'); // 指定处理提交的action标识 echo '<input type="hidden" name="action" value="send_custom_mail">'; ?> <table class="form-table"> <tr valign="top"> <th scope="row">收件人邮箱</th> <td><input type="email" name="recipient_email" class="regular-text" required></td> </tr> <tr valign="top"> <th scope="row">邮件内容</th> <td><textarea name="mail_content" rows="8" class="large-text" required></textarea></td> </tr> </table> <?php submit_button('发送邮件'); ?> </form> </div> <?php }
3. 处理表单提交请求
添加提交处理函数,完成邮件发送逻辑:
function handle_custom_mail_send() { // 验证请求合法性 if (!isset($_POST['mail_sender_nonce']) || !wp_verify_nonce($_POST['mail_sender_nonce'], 'mail_sender_action')) { wp_die('请求验证失败'); } if (!current_user_can('manage_options')) { wp_die('你没有权限执行此操作'); } // 清洗并验证用户输入 $recipient = sanitize_email($_POST['recipient_email']); $content = wp_kses_post($_POST['mail_content']); if (!is_email($recipient) || empty($content)) { wp_redirect(add_query_arg('mail_status', 'error', admin_url('admin.php?page=mail-sender'))); exit; } // 发送邮件 $subject = '来自WordPress仪表盘的邮件'; $headers = array('Content-Type: text/html; charset=UTF-8'); $mail_sent = wp_mail($recipient, $subject, $content, $headers); // 根据发送结果跳转回页面 $redirect_url = add_query_arg( 'mail_status', $mail_sent ? 'success' : 'error', admin_url('admin.php?page=mail-sender') ); wp_redirect($redirect_url); exit; } add_action('admin_post_send_custom_mail', 'handle_custom_mail_send');
注意事项
- 确保服务器支持PHP邮件函数,或通过SMTP插件(如WP Mail SMTP)配置邮件发送,避免
wp_mail函数失效。 - 代码中权限设置为
manage_options,仅管理员可使用,可根据需求调整为edit_posts等其他权限参数。 - 所有用户输入均做了转义与验证,避免XSS等安全风险。
内容的提问来源于stack exchange,提问作者Pudy
相关产品推荐
相关产品推荐

