/** * Displays comment "Parent" meta box. * * @see https://wpcodebook.com/comment-parent-wordpress/ * @see https://developer.wordpress.org/reference/classes/wp_comment/ * @see https://developer.wordpress.org/reference/hooks/add_meta_boxes_comment/ * @see https://developer.wordpress.org/reference/functions/add_meta_box/ * @see https://developer.wordpress.org/reference/functions/wp_nonce_field/ * * @param WP_Comment $comment Comment object. */ add_action( 'add_meta_boxes_comment', function ( $comment ) { add_meta_box( 'wpcodebook-comment-parent', __( 'Parent' ), function ( $comment ) { printf( '<input type="number" min="0" name="%s" value="%d">', 'wpcodebook_comment_parent', $comment->comment_parent ); wp_nonce_field( "wpcodebook-comment-parent-{$comment->comment_ID}", '_wpcodebook_nonce' ); }, 'comment', 'normal' ); } ); /** * Saves comment "Parent" meta box content. * * @see https://wpcodebook.com/comment-parent-wordpress/ * @see https://developer.wordpress.org/reference/hooks/edit_comment/ * @see https://developer.wordpress.org/reference/functions/wp_update_comment/ * @see https://developer.wordpress.org/reference/functions/wp_verify_nonce/ * * @param int $comment_id Comment ID. */ add_action( 'edit_comment', function ( $comment_id ) { if ( isset( $_POST['wpcodebook_comment_parent'] ) ) { // Comment parent ID $comment_parent = absint( $_POST['wpcodebook_comment_parent'] ); unset( $_POST['wpcodebook_comment_parent'] ); // Check nonce if ( ! isset( $_POST['_wpcodebook_nonce'] ) || ! wp_verify_nonce( $_POST['_wpcodebook_nonce'], "wpcodebook-comment-parent-{$comment_id}" ) ) { wp_die( esc_html__( 'Invalid nonce.' ) ); } // Set comment parent wp_update_comment( array( 'comment_ID' => $comment_id, 'comment_parent' => $comment_parent, ) ); } } );