WP_List_Table bulk action admin notice

Aiyaz Khorajia asked
php wordpress custom-wordpress-pages
via

I’m using WordPress WP_List_Table to show all request list, I’ve custom bulk action to approve and reject user request but whenever bulk action executed, I want to add admin notice but it not working, I think page is redirecting.

function process_bulk_action() {
    if( 'approve'===$this->current_action() )
    {
        $objCustomUserRoles = new CustomUserRoles();
        if(!empty($_REQUEST['wp_premium_users_request']))
        {
           foreach ($_REQUEST['wp_premium_users_request'] as $key => $value) 
           {
               $objCustomUserRoles->updateCustomerToPremium($value);
           }
           add_action( 'admin_notices', 'my_update_notice');
        }
    }
}

function my_update_notice() {
?>
<div class="updated notice">
    <p><?php _e( 'User approved!', 'avia_framework' ); ?></p>
</div>
<?php
}   


Answer
via

Your add_action( 'admin_notices', 'my_update_notice'); line is good, and the action handling function that you’ve attached there, is also good. The problem then, has to do with exactly when and where the process_bulk_action() function that you’re working with is being called upon.

Remember, the admin_notices hook in WordPress is fired in the header. If your process_bulk_action() function is being utilized by a theme or plugin that has in fact hooked into another action that actually comes after the admin_notices event has already taken place, then your notice will simply never be seen. No error, just nothing. You simply hooked-in too late.

To correct this, move the usage of this process_bulk_action() function to an earlier hook; i.e., one that is fired before admin_notices takes place. I suggest admin_init. That way your action handler will actually be called upon when it should be, and the notice will be seen as expected.

Also be sure that you don’t have any other code that would redirect a user away from the PHP process that is handling the form submission, before the notice is even seen; i.e., if a user is redirected before the HTML markup loads, the notice will not be seen then either.


Aside: The code that you posted is vulnerable to attacks of various kinds. Please be sure to properly sanitize the request data that you’re working with before using it.

In short, you can’t know for certain (unless you check), that $_REQUEST['wp_premium_users_request'] is in fact an array. In addition, you can’t know for certain what the array actually contains. So before using anything in that untrusted source of data that comes from a web browser form submission, be sure to validate/sanitize thoroughly.

In addition, be sure to use and verify an Nonce.

Share This
Posted in: