【问题标题】:Wordpress - Best way to use 'Flash Messages' for front-end usersWordpress - 为前端用户使用“Flash Messages”的最佳方式
【发布时间】:2019-11-23 17:39:37
【问题描述】:

一些背景知识:我开发了一个带有表单的 wordpress 插件。我需要一种方法来通知用户如果他们填写表格搞砸了。我最初的倾向是 php 会话变量。我将各种代码添加到我的插件中以使其正常工作,包括标题顶部的session_start(),它破坏了一些东西。所以我开始研究向用户显示消息的最佳方式。

我可以使用 cookie 作为 php 会话的替代方案,但我的问题是:

在 Wordpress 中设置前端消息的最佳方式是什么? 请注意,我是 wordpress 新手。 我听说过 Wordpress 全局变量? Wordpress 是否提供了诸如我可以设置的全局变量之类的东西,这些变量可以在任何地方访问?那会奏效。是否有一些我应该研究的插件(我不想让这个膨胀)。 Cookie 是最佳途径吗?

这是一个可以说明我想要完成的代码的 sn-p:

前端表单(简码)

  <form method='POST'class="kb_donation_form" action="<?= // my action ?>">

            <div class="form-group">
                <label for="kb_first_name">First Name</label>
                <input type="text" class="form-control" id="kb_first_name" name="kb_first_name" placeholder="First Name">
            </div>

            <div class="form-group">
                <label for="kb_last_name">Last Name</label>
                <input type="text" class="form-control" id="kb_last_name" name="kb_last_name" placeholder="First Name">
            </div>
            <div class="form-group">
                <label for="kb_email">Email</label>
                <input type="email" class="form-control" id="kb_email" name="kb_email" placeholder="Email Address">
            </div>

            <div class="form-group">
                <label for="kb_grad_year">Graduation Year</label>
                <select id="kb_grad_year" name="kb_grad_year" class="form-control">
                    <option value="friend">I am just a friend.</option>
                    <option value="1950">1950</option>
                </select>
            </div>

            <div class="form-group">
                <label for="kb_donation_amount">Donation Amount</label>
                <input type="text" class="form-control" id="kb_donation_amount" name="kb_donation_amount" placeholder="100.00">
            </div>

            <div class="form-group">
                <input type="submit" name="submit" value="Make Donation" class="btn btn-default">
            </div>
        </form>

后处理程序代码:

if(isset($_POST['submit'])) {
    if(
        !empty($_POST['kb_first_name']) &&
        !empty($_POST['kb_last_name']) &&
        !empty($_POST['kb_email']) &&
        !empty($_POST['kb_grad_year']) &&
        !empty($_POST['kb_donation_amount'])
       ) {
        // All Data Is Set

        // Make sure email is valid format
        $email = filter_var($_POST['kb_email'], FILTER_VALIDATE_EMAIL);

        if(!empty($email)) { // ect.. ect..}
else {
// screw up
// Notify the user
// $_SESSION['error'] = 'You Screwed Up' === NEED ALTERNATIVE
}

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    首先,不要提供任何 PHP 脚本链接,就像您使用 action="/kb-donations/includes/handler.php"

    它会引发安全问题。这不是 WordPress 的做事方式。

    要处理您的表单,请使用“admin_post”(admin_post_YOUR_ACTION) 和“admin_post_nopriv” (admin_post_nopriv_YOUR_ACTION) 操作。这是一个很好的解释:

    https://www.sitepoint.com/handling-post-requests-the-wordpress-way/

    然后你需要设置 flash messages 来给用户提供错误信息或成功信息。

    如果它是后端表单,则使用“admin_notices”操作。这是一个很好的解释:

    https://premium.wpmudev.org/blog/adding-admin-notices/

    对于前端表单:

    我。您可以使用您的表单模型显示闪存消息(通过存储在备份模型的“错误”私有变量中的成功或错误消息)

    或 ii。您可以使用“template_notices”操作。

    或 iii。您可以使用“session_start”(启动会话,将数据存储到会话中并在显示后将其清除)解决方案。

    使用全局变量总是一个坏主意。

    【讨论】:

    • 感谢您的反馈。值得赞赏。这是我为 Wordpress 开发的第一个插件,从那时起我的成长迅速。
    【解决方案2】:

    这是一个带有 Flash 消息的重定向类

    class Flash
    {
    
        const FLASH_KEYS = 'flash_message_stored_keys';
        const SKIP_FLAG = 'skip_flash_clean_up';
        private $xRedirectBy = 'flash';
        private $statusCode = 302;
        private $redirectUrl;
    
        public static function init()
        {
            if (!defined('FLASH_INIT')) {
                // ensure session is started
                if (session_status() !== PHP_SESSION_ACTIVE) {
                    session_start();
                }
                // clean up flash messages from session on script finishing point
                register_shutdown_function([Flash::class, 'cleanUpFlashMessages']);
                // define flash is initialized
                define('FLASH_INIT', true);
            }
        }
    
        /**
         * Its a callback for (@register_shutdown_function) which registered in constructor
         */
        public static function cleanUpFlashMessages()
        {
            if (!defined(self::SKIP_FLAG)) {
    
                if (isset($_SESSION[self::FLASH_KEYS])) {
    
                    //clean flash messages by using stored keys
                    foreach ($_SESSION[self::FLASH_KEYS] as $message_key) {
                        unset($_SESSION[$message_key]);
                    }
    
                    //then clean stored keys itself
                    unset($_SESSION[self::FLASH_KEYS]);
                }
            }
        }
    
        /**
         * @param string $key flash message key in session storage
         * @param string $message message value
         *
         * @return Flash
         */
        public function message($key, $message)
        {
            $_SESSION[self::FLASH_KEYS][] = $key;
            $_SESSION[$key] = $message;
    
            //skip cleaning once for redirection
            if (!defined(self::SKIP_FLAG)) {
                define(self::SKIP_FLAG, true);
            }
    
            return $this;
        }
    
        /**
         * @param $url
         *
         * @return Flash
         */
        public function redirectLocation($url)
        {
            $this->redirectUrl = $url;
            return $this;
        }
    
        /**
         * @param $status
         *
         * @return Flash
         */
        public function withStatus($status = 302)
        {
            $this->statusCode = $status;
            return $this;
        }
    
        /**
         * @param $xRedirectBy
         *
         * @return Flash
         */
        public function redirectBy($xRedirectBy = 'flash')
        {
            $this->xRedirectBy = $xRedirectBy;
            return $this;
        }
    
        public function redirect()
        {
            if (!isset($this->redirectUrl)) {
                $this->redirectBack();
                return;
            }
    
            @header("X-Redirect-By: $this->xRedirectBy", true, $this->statusCode);
            @header("Location: $this->redirectUrl", true, $this->statusCode);
            exit();
        }
    
        public function redirectBack()
        {
            $this->redirectUrl = $_SERVER['HTTP_REFERER'];
            $this->redirect();
        }
    
    }
    

    在你的functions.php中初始化这个类 l Flash::init(); 然后使用这个类来重定向一个flash消息。

            $flash = new Flash();
    
            if ( $success ) {
                $flash->message( 'success', 'Your message sent successfully!' )
                      ->redirectLocation( site_url( '/contact' ) )
                      ->redirectBy( 'contact' )
                      ->redirect();
            }
    

    在前端检查会话中是否存在您的消息密钥,做您的特殊工作...... 快乐编码

    【讨论】:

    • 酷类。我自己一直在使用类似的东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多