In the interest of helpfulness, here’s one solution to the problem above. The reason why it doesn’t work the way you expect is because wordpress is issuing a redirect between the time the save_post
action is called and the time the admin_notices
action is called. So the action you’ve attached to admin_notices
does not exist at the time that action is actually called.
In order to work around this, you can store the message temporarily during save_post
and then retrieve it after the redirect. Modifying your pseudocode example from above:
add_action('save_post', 'functionx'); // called before the redirect
add_action('admin_head-post.php', 'add_plugin_notice'); // called after the redirect
function add_plugin_notice() {
if (get_option('display_my_admin_message')) { // check whether to display the message
add_action('admin_notices' , create_function( '', "echo '" . get_option('my_admin_message') . "';" ) );
update_option('display_my_admin_message', 0); // turn off the message
}
}
// essentially the same as your original functionx, except the message is stored and activated for display
function functionx () {
if (functionA()) {
update_option('my_admin_message', 'Function A Returned 1.');
} else {
update_option('my_admin_message', 'Function A Returned 0.');
}
update_option('display_my_admin_message', 1); // turn on the message
}
function functionA () {
return (rand(1, 2) % 2); // dummy function - randomly return true or false
}
Note that this example uses the specific action admin_head-post.php
after the redirect – this will prevent the add_plugin_notice
function from even being added to admin_notices unless you’re looking at edit.php. If you were writing a notice to appear on another page, you would need to modify the action name to refer to that page, or use this generic one instead:
add_action('admin_head', 'add_plugin_notice');
(Also, if you’re unfamiliar with get_option
and update_option
, have a look at the documentation for update_option
.)