Magento 2 - Create order programmatically and add products with custom options

Magento 2 - Create order programmatically and add products with custom options

July 6, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento 2 - Create order programmatically and add products with custom options

Magento 2 - Create Order Programmatically and Add Products with Custom Options

In this post, we’ll guide you through creating an order programmatically in Magento 2 (version 2.1.6) and adding products with custom options. We’ll provide a step-by-step solution using the given code as a starting point.

Prerequisites

Before proceeding, ensure you have:

  • A working Magento 2 installation.
  • Familiarity with OOP concepts in PHP.

The Given Code

The provided code initializes various class dependencies and constructs a function called createOrderNew. Let’s break down the key components:

  1. Constructor: This is where we initialize all the required objects, services, and repositories needed for creating an order.

  2. createOrderNew Function: This is the main function responsible for creating a new order. It takes an array of order data as its parameter.

Step-by-Step Solution

Step 1: Initialize Store, Website, and Customer

The code first initializes the store and website IDs based on the currently loaded store. If the customer with the given email doesn’t exist, it creates a new one:

$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);

// Check if the customer exists
if (!$customer->getEntityId()) {
    // If not available, create this customer
    $customer->setWebsiteId($websiteId)
        ->setStore($store)
        ->setFirstname($orderData['shipping_address']['firstname'])
        ->setLastname($orderData['shipping_address']['lastname'])
        ->setEmail($orderData['email'])
        ->setPassword($orderData['email']);
    $customer->save();
}

Step 2: Create an Empty Cart and Assign the Customer

Next, it creates an empty cart using the cartManagementInterface:

$cart_id = $this->cartManagementInterface->createEmptyCart();
$cart = $this->cartRepositoryInterface->get($cart_id);
$cart->setStore($store);

Then, it assigns the created customer to the cart:

$customer = $this->customerRepository->getById($customer->getEntityId());
$cart->assignCustomer($customer); // Assign quote to customer
$cart->save();

Step 3: Add Products with Custom Options

The code iterates through the order items and adds each product to the cart, taking into account various product types (simple, configurable, bundle, grouped):

foreach ($orderData['items'] as $item) {
    foreach ($item as $product_item) {
        // Load the product
        $product = $this->_productFactory->create()->load($product_item['product_id']);

        // Add custom options
        if (array_key_exists('options', $product_item) && $product_item['options']) {
            $params['options'] = json_decode(json_encode($product_item['options']), true);
        }

        // Set parameters based on product type
        switch ($product->getTypeId()) {
            case 'configurable':
                $params['super_attribute'] = $product_item['super_attribute'];
                break;
            case 'bundle':
                $params['bundle_option'] = $product_item['bundle_option'];
                $params['bundle_option_qty'] = $product_item['bundle_option_qty'];
                break;
            case 'grouped':
                $params['super_group'] = $product_item['super_group'];
                break;
        }

        // Add the product to the cart
        try {
            $objParam = new \Magento\Framework\DataObject();
            $objParam->setData($params);
            $cart->addProduct($product, $objParam);
        } catch (Exception $e) {
            // Handle the exception
            // ...
        }
    }
}

Step 4: Set Shipping and Payment Information

The code sets the shipping address, shipping method, payment method, and gathers totals for the cart:

$cart->getBillingAddress()->addData($orderData['shipping_address']);
$cart->getShippingAddress()->addData($orderData['shipping_address']);

// Set shipping method (free shipping in this case)
$this->shippingRate
    ->setCode('freeshipping_freeshipping')
    ->getPrice(1);

$shippingAddress = $cart->getShippingAddress();
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()->setShippingMethod('flatrate_flatrate');

// Set payment method (check/money order in this case)
$cart->setPaymentMethod('checkmo');

// Collect totals and save the cart
$cart->collectTotals();

Step 5: Place Order and Create Invoice

Finally, it places the order using the cartManagementInterface:

$cart = $this->cartRepositoryInterface->get($cart->getId());
$order_id = $this->cartManagementInterface->placeOrder($cart->getId());

if ($orderData['status'] == 4) {
    return $this->createInvoice($order_id);
}

return $order_id;

Common Issues and Troubleshooting

Custom Options Not Being Saved

In the provided code, the custom options are not being saved to the order correctly. To fix this:

  1. Make sure the custom option IDs in your options array match the actual option IDs in your Magento store.

  2. Ensure that you have configured the correct product attributes to save the custom options during the order creation process.

Missing or Incorrect Product Options

Double-check that the product options are correctly set in the $item['options'] array passed to the addProduct method. Make sure the option IDs, values, and prices match your Magento configuration.

Wrapping Up

Creating orders programmatically in Magento 2 is a powerful feature that allows for automated order processing and integration with external systems. The provided code serves as a solid foundation, but it requires some adjustments to handle custom options correctly.

For more detailed information on working with orders and quotes in Magento 2, we recommend checking out the official documentation:

Remember to always test your code thoroughly before deploying it to a production environment.

That’s it for this post! We hope you found the solution helpful and informative. If you have any further questions or need additional guidance, feel free to reach out to our team at LaravelCompany.

Magento 2 Catalog Email Orders

Our network