Using WordPress ‘comment_on_trash’ PHP action

The comment_on_trash WordPress PHP action fires when a comment is attempted on a trashed post.

Usage

add_action('comment_on_trash', 'your_custom_function', 10, 1);

function your_custom_function($comment_post_id) {
  // your custom code here
}

Parameters

  • $comment_post_id (int) – The ID of the trashed post.

More information

See WordPress Developer Resources: comment_on_trash

Examples

Notify admin when a comment is attempted on a trashed post

This code sends an email notification to the admin when someone tries to comment on a trashed post.

add_action('comment_on_trash', 'notify_admin_on_trashed_comment', 10, 1);

function notify_admin_on_trashed_comment($comment_post_id) {
  $admin_email = get_option('admin_email');
  $subject = 'Comment attempted on trashed post';
  $message = 'A user tried to comment on a trashed post with ID: ' . $comment_post_id;

  wp_mail($admin_email, $subject, $message);
}

Log comment attempts on trashed posts

This code logs the trashed post ID when a comment attempt is made.

add_action('comment_on_trash', 'log_trashed_comment_attempts', 10, 1);

function log_trashed_comment_attempts($comment_post_id) {
  error_log('Comment attempted on trashed post ID: ' . $comment_post_id);
}

Redirect user when attempting to comment on a trashed post

This code redirects the user to the homepage when they try to comment on a trashed post.

add_action('comment_on_trash', 'redirect_user_trashed_comment', 10, 1);

function redirect_user_trashed_comment($comment_post_id) {
  wp_redirect(home_url());
  exit;
}

Display a custom message when a user tries to comment on a trashed post

This code displays a custom message to the user when they attempt to comment on a trashed post.

add_action('comment_on_trash', 'display_custom_message', 10, 1);

function display_custom_message($comment_post_id) {
  wp_die('Sorry, you cannot comment on a trashed post.', 'Comment not allowed');
}

Prevent comment form from showing on trashed posts

This code prevents the comment form from showing on trashed posts by checking the post status.

add_filter('comments_open', 'hide_comment_form_on_trashed_posts', 10, 2);

function hide_comment_form_on_trashed_posts($open, $post_id) {
  $post_status = get_post_status($post_id);

  if ($post_status == 'trash') {
    return false;
  }

  return $open;
}