How to add a Class to the body element when a new blog post is published?

I need to add a class to my html (either the body tag or another element) after a new blog post is published, and then remove the class after a number of days.

New blog post published >>
Body gets class new-post >>
3 days later >>
new-post is removed from the body.

Read More

Any ideas how I would achieve this.

Thanks in advance
Dave

Related posts

Leave a Reply

2 comments

  1. You could try this:

    <?php
    
        $blogPosts = get_posts(array('post_type' => 'post', 'status' => 'publish',));
        $newestPostDate = get_the_time('U',$blogPosts[0]->ID);
        $threeDaysOld = strtotime('-36 hours');
    
        if ($newestPostDate > $threeDaysOld) { ?>
    
            <script type="text/javascript">
                jQuery(document).ready(function() {
                    if (jQuery('body').hasClass('new-post')) {
                        // do nothing
                    } else {
                        jQuery('body').addClass('new-post');        
                    }
                });
            </script>
    
        <?php } ?>
    

    You could change 'post_type' => 'post' to any post type you want, currently it is set to get the main blog posts. This piece of code with get the newest post, and check if its date is more than 3 days old. If the date is less than 3 days old, it will check if the body already has the class new-post, if it does it will do nothing, but if it does not it will add the class. It would fire each time the page loads that you have this code on. Place it on the page template file you want it to check for anywhere after the opening HTML <body> tag. Hopefully this helps.