The comment_closed WordPress PHP action fires when a comment is attempted on a post that has comments closed.
Usage
add_action('comment_closed', 'my_custom_function', 10, 1); function my_custom_function($comment_post_id) { // Your custom code here }
Parameters
$comment_post_id
(int): The ID of the post where the comment was attempted.
More information
See WordPress Developer Resources: comment_closed
Examples
Display a message when comments are closed
Display a custom message when a user tries to comment on a post with comments closed.
add_action('comment_closed', 'display_custom_message', 10, 1); function display_custom_message($comment_post_id) { echo 'Comments are closed for this post. Please come back later.'; }
Log comment attempts on closed posts
Log the details of comment attempts on closed posts for further analysis.
add_action('comment_closed', 'log_comment_attempt', 10, 1); function log_comment_attempt($comment_post_id) { // Log the comment attempt error_log("Comment attempted on closed post ID: {$comment_post_id}"); }
Send an email notification for comment attempts on closed posts
Notify the site administrator when a comment is attempted on a closed post.
add_action('comment_closed', 'notify_admin_comment_attempt', 10, 1); function notify_admin_comment_attempt($comment_post_id) { $admin_email = get_option('admin_email'); $subject = "Comment attempted on closed post ID: {$comment_post_id}"; $message = "A comment was attempted on the closed post with ID: {$comment_post_id}."; wp_mail($admin_email, $subject, $message); }
Redirect users after a comment attempt on a closed post
Redirect users to a custom page after they attempt to comment on a closed post.
add_action('comment_closed', 'redirect_user_after_comment_attempt', 10, 1); function redirect_user_after_comment_attempt($comment_post_id) { $redirect_url = 'https://example.com/custom-page'; wp_redirect($redirect_url); exit; }
Add a comment_closed meta key to the post
Add a meta key to the post when a comment is attempted, to track closed comment attempts.
add_action('comment_closed', 'add_comment_closed_meta', 10, 1); function add_comment_closed_meta($comment_post_id) { add_post_meta($comment_post_id, 'comment_closed_attempt', 1); }