Show message from backend
-
13-01-2021 - |
Вопрос
I need to show messages on wordpress page editor, when a page is updated. I know there is a admin_notice
hook to show messages. I have a save_post_page
perfectly working on my code, but I need to know how to connect both of them and I don't know why?
Any help would be appreciate,
Best regards,
Ismael
Решение
The problem is that when a post is saved, there's a redirect back to the edit post page and the admin_notices action never runs. This means that any admin notice you put on any of the save post actions (save_post, transition_post_status, etc.) will be thrown away (since they're not persistent) during that redirect.
The workaround is to save a state (user settings/user meta, post meta, transients, options) which would signal that an admin notice should be shown, and look for that state on the next request.
add_action( 'save_post', function( $post ) {
// some checks here
update_user_option( get_current_user_id(), '_my_show_notice', true );
});
add_action( 'admin_notices', function() {
if ( get_user_option( '_my_show_notice' ) ) {
delete_user_option( get_current_user_id(), '_my_show_notice' );
echo '<div class="notice notice-success"><p>Some notice</p></div>';
}
});
Hope that helps!