Wordpress - Best way to use 'Flash Messages

2019-07-25 21:25发布

Some background: I developed a wordpress plugin with a form in it. I need a way to notify the user if they mess up filling out the form. My initial inclination was php session variables. I added the various pieces of code to my plugin to make this work including the session_start() at the top of my header which broke things. So i started doing research on the best way to show messages to the user.

I can use cookies as an alternative to php sessions but my question is:

What is the best way to set up front-end messages inside of Wordpress? I am new to wordpress mind you. I heard of Wordpress global variables? Does Wordpress provide something like global variables I can set which can be accessed anywhere? That would work. Is there some plugin i should look into (I would hate to bloat this). Are cookies the best route?

Here is a snippet of code that may illustrate what I am trying to accomplish:

Front End Form (shortcode)

  <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>

The post handler code:

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
2条回答
戒情不戒烟
2楼-- · 2019-07-25 21:47

It's a redirection class with flash messages

    <?php


namespace App\Core;


class Flash
{

    protected static $instance = null;

    const FLASH_MESSAGE_SKIP_CLEAN = 'flash_message_flag';
    const FLASH_MESSAGE_STORED_KEYS = 'flash_message_keys';
    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 (isset($_SESSION[self::FLASH_MESSAGE_SKIP_CLEAN])) {

            //just skip cleaning flash messages
            unset($_SESSION[self::FLASH_MESSAGE_SKIP_CLEAN]);

        } else if (isset($_SESSION[self::FLASH_MESSAGE_STORED_KEYS])) {

            //clean flash messages by using stored keys
            foreach ($_SESSION[self::FLASH_MESSAGE_STORED_KEYS] as $message_key) {
                unset($_SESSION[$message_key]);
            }

            //then clean stored keys itself
            unset($_SESSION[self::FLASH_MESSAGE_STORED_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_MESSAGE_STORED_KEYS][] = $key;
        $_SESSION[$key] = $message;
        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()
    {
        //skip cleaning once for redirection
        $_SESSION[self::FLASH_MESSAGE_SKIP_CLEAN] = true;
        @header("X-Redirect-By: $this->xRedirectBy", true, $this->statusCode);
        @header("Location: $this->redirectUrl", true, $this->statusCode);
    }

}

init this class in your functions.php l Flash::init(); then use this class to redirect with a flash message.

        $flash = new Flash();

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

in front end side check if your message key exists in the sessions, do your special jobs ... happy coding

查看更多
霸刀☆藐视天下
3楼-- · 2019-07-25 21:49

First of all, don't provide any of your PHP script link like you did by using action="/kb-donations/includes/handler.php"

It can raise security issues. It's not a WordPress way of doing things.

To process your form use "admin_post"(admin_post_YOUR_ACTION) and "admin_post_nopriv" (admin_post_nopriv_YOUR_ACTION) actions. Here is a good explanation:

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

and then you need to set flash messages to give error messages or success messages to the users.

If its a backend form, then use "admin_notices" action. Here is a good explanation:

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

For front-end forms :

i. You can use your form model to show the flash messages (success or error messages by storing in "error" private variable of the backed up model)

or ii. you can use "template_notices" action.

or iii. you can use "session_start" (starting a session, storing data into the session and clearing it after display) solution.

Using global variable is always a bad idea.

查看更多
登录 后发表回答