Update post date on every new comment?

The question:

I would like to update a post on every new comment, so that the Last Modified Date is always up to date on the sitemap.

How can i do this?


The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

From what i understand, you want to change the post’s modification time whenever a comment is left on your post. For this, you need to hook into the wp_insert_comment hook and update the post’s date manually:

function update_post_time($comment_id, $comment_object) {
    // Get the post's ID
    $post_id = $comment_object->comment_post_ID;
    // Double check for post's ID, since this value is mandatory in wp_update_post()
    if ($post_id) {
        // Get the current time
        $time = current_time('mysql');
        // Form an array of data to be updated
        $post_data = array(
            'ID'           => $post_id, 
            'post_modified'   => $time, 
            'post_modified_gmt' =>  get_gmt_from_date( $time )
        // Update the post
        wp_update_post( $post_data );

Note that this will create a revision for the post each time a comment is created.

If your sitemap plugin uses the post_date instead of post_modified, you can use this instead:

$post_data = array(
    'ID'           => $post_id, 
    'post_date'   => $time, 
    'post_date_gmt' =>  get_gmt_from_date( $time )

However, this might cause problems, and mess post’s order in archives and homepage, since it changes the post’s creation date, not modification date.

Method 2

That may change the order of posts on your main page, depending on your theme.

There are ways to display the links to the pages with recent comments.

But, you will need to have your theme (child theme, hopefully, since you don’t want to change theme code) add code which uses a hook on comment save. For instance, you could use the wp_insert_comment() hook, as described in this link: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_comment

There are other hooks that can be used during a comment save, depending on when you want things to happen.

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment