How to add Order Comments History by order id programmatically in Magento 2?

Add Magento Order History Comment using the programmatic approach for the orders.

You need to use the interface, Magento\Sales\Api\OrderStatusHistoryRepositoryInterface to add a comment. You can also set the order status for the comment.

You can check to add sales order status history data programmatically in Magento 2.

You have to Retrieve the Order ID to add a comment, load the order object by the ID, add a status history comment for the given sales order with some code snippet,

<?php

namespace Jesadiya\StatusHistoryComment\Model;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\Data\OrderStatusHistoryInterface;
use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface;
use Psr\Log\LoggerInterface;

class Comment
{
    public function __construct(
        private readonly OrderStatusHistoryRepositoryInterface $orderStatusRepository,
        private readonly OrderRepositoryInterface              $orderRepository,
        private readonly LoggerInterface                       $logger
    ) {
    }

    /**
     * add comment to the order history
     *
     * @param int $orderId
     * @return OrderStatusHistoryInterface|null
     */
    public function addCommentToOrder(int $orderId): ?OrderStatusHistoryInterface
    {
        $order = null;
        try {
            $order = $this->orderRepository->get($orderId);
        } catch (NoSuchEntityException $exception) {
            $this->logger->error($exception->getMessage());
        }
        $orderHistory = null;
        if ($order) {
            $comment = $order->addCommentToStatusHistory(
                'Order Processing Export Failed',
                'pending' // order status
            );
            try {
                $orderHistory = $this->orderStatusRepository->save($comment);
            } catch (\Exception $exception) {
                $this->logger->critical($exception->getMessage());
            }
        }
        return $orderHistory;
    }
}

You can pass order status for the comment if you want using the second parameter in the addStatusHistoryComment($message, $status) method.

Call method with a required parameter,

$orderId = 5;
$statusHistoryComment = $this->addCommentToOrder($orderId);

Output:

order status History Comment
order status History Comment Magento 2