Optional Title Field for Comments
Adds an optional "Title" field to the comment form and shows it as a heading above the comment, handy for reviews and longer discussions.
Opens WPIDE on
Code
add_filter( 'comment_form_field_comment', function ( $field ) {
return '<p class="comment-form-title"><label for="wpide-comment-title">Title (optional)</label><input type="text" id="wpide-comment-title" name="wpide_comment_title" maxlength="100"></p>' . $field;
} );
add_action( 'comment_post', function ( $comment_id ) {
$title = isset( $_POST['wpide_comment_title'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_comment_title'] ) ) : '';
if ( '' !== $title ) {
add_comment_meta( $comment_id, 'wpide_comment_title', mb_substr( $title, 0, 100 ), true );
}
} );
add_filter( 'comment_text', function ( $text, $comment = null ) {
if ( ! $comment || is_admin() ) {
return $text;
}
$title = (string) get_comment_meta( $comment->comment_ID, 'wpide_comment_title', true );
return '' !== $title ? '<p class="comment-title"><strong>' . esc_html( $title ) . '</strong></p>' . $text : $text;
}, 9, 2 );
Notes
Titles are limited to 100 characters and stored as comment meta named wpide_comment_title.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.