Вопрос

In my (admin) plugin I want to display a message using admin_notices action on successful sending of mail. Currently it is not displaying. I know this has something to do with the order of events, but I cannot figure out how to structure it so that the message displays.

Currently I'm adding the admin_notices action from within an init action callback. I'm not sure if this is allowed and therefore this may be the issue. However, if I add it to the __construct method, how can I get it to know that the mail has been sent?

Currently my Send_mail class looks something like:

class Send_mail {
    public function __construct() {
        add_action('init', array($this, 'send_mail'), 30 );
    }

    public function send_mail() {
        if (!isset($_POST['send-confirmation-true'])) {
            return;
        }

        // wp_mail() functionality
        // returns true on successful send

        if ($mail_sent == true) {
            add_action('admin_notices', array($this, 'show_admin_notice') );
        }
    }

    public function show_admin_notice() {
        // output admin notice html
    }
}

=== EDIT ===

After doing some testing, I've found out that actions called after the following if-statement:

if (!isset($_POST['send-confirmation-true'])) {
    return;
}

only work if they are hooked to an action that is either load-(page) (in my case: load-post.php) or before in the action order list. The action I need is admin_notices and therefore does not get added. What is causing this behaviour?

Это было полезно?

Решение

This workaround is far from ideal, but it gets the job done.

On $mail_sent == true set a post meta. In the __construct function add a callback to the admin_head action that checks whether the post meta has been set. If yes, delete the post meta and add the admin_notices action with the callback to the desired admin notice.

class Send_mail {
    public function __construct() {
        add_action( 'init', array($this, 'send_mail'), 30 );
        add_action( 'admin_head', array($this,'check_mail_sent') );
    }

    public function send_mail() {
        if (!isset($_POST['send-confirmation-true'])) {
            return;
        }

        // wp_mail() functionality
        // returns true on successful send

        if ($mail_sent == true) {
            update_post_meta($campaign_id, 'mail_sent', 'yes');
        }
    }

    public function check_mail_sent() {
        global $post;
        $mail_sent = get_post_meta( $post->ID, 'mail_sent', true );

        if($mail_sent == 'yes') {
            delete_post_meta($post->ID, 'mail_sent');
            add_action('admin_notices', array($this, 'show_admin_notice') );
        } else if ($mail_sent == 'no') {
            // Can handle a mail fail notice here if needed
        }
    }

    public function show_admin_notice() {
        // output admin notice html
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top