I want to make a notification bar in my Wordpress website, that will be displayed when there is a new post published. Unfortunately, I have some problems with getting the code work.
GOAL
What the goal is, is to let the user know that there are new posts available for them on the website with a notification bar. So the code should check if the amount of posts is increased. If yes, I want to show the notification bar on the website for two days.
THE PROBLEM
The following code will only outputs the total number of posts from each post type that I have specified in the $post_types
array. The if statement doesn’t work correctly. When I publish a new post, delete it and post another, it will not update the number in the database. Only if I post after I delete an older one, the value will increase.
MY CODE
The code below will now only echos the post type name and number of posts.
$args = array(
'public' => true,
'_builtin' => false
);
$post_types = array( 'post', 'roosters', 'downloads', 'reglements', 'alv' );
foreach ( $post_types as $post_type ) {
// variable
$postCountTotal = wp_count_posts( $post_type )->publish;
echo '<strong>' . $post_type . '</strong>';
echo ' has total posts of : ' . $postCountTotal;
echo '<br>';
// First read the previous post count value from the databse so we can compare the old value with the new one
// EDIT: use 0 as the default value if no data in database - first run
$previousCount = get_option( 'post_count_total', 0 );
if ( $postCountTotal != $previousCount ) {
//echo 'New post detected';
update_option( 'post_count_total', $postCountTotal );
} elseif ( '' == $postCountTotal && $previousCount ) {
delete_option( 'post_count_total', $previousCount );
}
}
echo $postCountTotal;