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?
Thanks.
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?
Thanks.
Share Improve this question edited Jun 10, 2017 at 8:37 Johansson 15.4k11 gold badges43 silver badges79 bronze badges asked Jun 9, 2017 at 21:33 boorockboorock 618 bronze badges2 Answers
Reset to default 3From 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:
add_action('wp_insert_comment','update_post_time',99,2);
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.
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/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.