Counting messages to determine if there is a new message is wasting resources and is inaccurate, since switching to message status can affect the score. For example, as you said, if a message is deleted and a new one is published, the counter will remain the same
To complete this work, we need to complete the following workflow
WORKSFLOW
We need to determine when the publication is published. This can be done using the transition_post_status
action hook. This hook is triggered every time the message status changes. Even if the message is updated, the status changes.
We should only do something when a new message is published, so we need to check the status of the message before and after publication (the "new" status does not work here, as I expected it to work, so I refused this idea).
Next, the new post object will be saved in the wp_options
table, where we can get it later in the template and use it to display the notification panel. The functions to use here will be add_option()
to create our variant if it does not exist, and update_option()
if this parameter already exists.
The post object is now stored in the wp_options
table. Now we should get this option in the function or template file. We will use get_option()
. From the saved post object we need to get post_date_gmt
to use it for comaprison, and we need to determine the exact time after 2 days
We also need the current time, which we can get with current_time()
In the end, we can compare the dates, and if the dates we are comparing are less than two days, we need to do our best, show the notification bar, if the comparison is more than two days, we either show nothing or something else
CODE
Here is the final code. I commented on this so that you can follow him.
In your functions.php add the following
add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) { //Check if our post status then execute our code if ( $new_status == 'publish' && $old_status != 'publish' ) { if ( get_option( 'new_post_notification' ) !== false ) { // The option already exists, so we just update it. update_option( 'new_post_notification', $post ); } else { add_option( 'new_post_notification', $post ); } } }, 10, 3 );
Now, in your template or user-defined function, if you want, add the following
// Get the new_post_notification which holds the newest post $notification = get_option( 'new_post_notification' ); if( false != $notification ) { //Get the post gmt date. This can be changed to post_date $post_date = strtotime( $notification->post_date_gmt ); //Get the current gmt time $todays_date = current_time( 'timestamp', true ); //Set the expiry time to two days after the posts is published $expiry_date = strtotime('+2 day', $post_date); if( $expiry_date > $todays_date ) { // Display your notification if two days has not been passed } }