When publishing a new post in WordPress I want to show an extra admin_notice to show a custom message. I'm using the admin_notices
hooks for this. I tested this and it works. What doesn't work is to show it when the post is published.
I tried a couple of methods including the ' publish_post'
hook. The hook is firing, when I put a var_dump('bla');exit();
I can see this working. I think the reason the admin_notices doesn't show is because the page is refreshing. So if there would be something like 'after_publish_post'
that'd be great but I cannot find it.
I also tried something I've found in a similar question:
if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) { echo "New post!"; exit();}
This also has no effect
--
What I have at this moment is:
add_action('publish_post', array($this,'onInsertPost')); //does work, function gets triggered
public function onInsertPost($post_id, $post, $update) {
add_action( 'admin_notices', array($this, 'info_text_news') );
}
public function info_text_news() {
$class = 'notice notice-info';
$message = __( 'My message', 'admin_notice' );
printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), $message);
}
Like I earlier said, all this code is working but togheter the notice is not showing up. I think because of the refreshing page after pressing the publish button.
I've found a solution to do this. I'm checking the post date and comparing it to the date of today. If the post is posted today it triggers the hook. In my case, one day is fine. If you need to only show it after post you can adjust it to checking the time also.
global $pagenow;
if ( $pagenow == 'post.php' ) {
$currentPost = get_post( $_GET['post'] );
$postdate = substr($currentPost->post_date, 0 , 10);
//if post type is post and post is published today show info message
if($currentPost->post_type == 'post' && $postdate == date('Y-m-d')) {
add_action( 'admin_notices', array($this, 'info_text_news') );
}
}