How to Get Configurable Product Options in Magento 2

How to Get Configurable Product Options in Magento 2

[Updated: March 16, 2026]

Configurable products drive most Magento stores, yet retrieving their options programmatically trips up even experienced developers. Blank dropdowns and missing child products waste hours.

This guide covers PHP code, admin setup, and troubleshooting for configurable product options in Magento 2.4.8.

Key Takeaways

  • PHP methods to retrieve configurable attributes and child products programmatically
  • Admin settings to display product options on category list pages
  • Code examples for templates, blocks, and GraphQL queries
  • Troubleshooting for missing options, wrong prices, and blank swatches
  • Performance considerations for stores with large configurable catalogs

What Are Configurable Product Options?

Configurable product options = product variations (size, color, material) managed under one parent SKU. Customers select their preferred combination without navigating to separate product pages.

Perfect for: Fashion stores, electronics retailers, any catalog with size/color variants

Not ideal for: Stores selling unique one-off items, digital products, or services

A configurable product in Magento 2 consists of a parent product linked to multiple simple (child) products. Each child product represents one specific combination of attributes. The parent product itself has no inventory. Stock is tracked at the child level.

For example, a T-shirt with 3 colors and 4 sizes creates 12 simple products under one configurable parent. The storefront shows a single product page with dropdown or swatch selectors.

Key characteristics in Magento 2.4.8:

  • Configurable attributes must have Global scope and use Dropdown, Visual Swatch, or Text Swatch input types
  • Child products can be Simple or Virtual but cannot include custom options
  • Stock status is semi-automatic, based on child product availability
  • Price display follows the lowest child price unless configured otherwise

Configurable Products vs Custom Options vs Product Variants

Understanding the difference prevents choosing the wrong product type:

Feature Configurable Product Custom Options Grouped Product
Separate SKU per variation Yes No Yes
Individual inventory tracking Yes No Yes
Swatch display on frontend Yes No No
Price per variation Yes Yes (price modifier) Yes
Display on list page Yes (with config) No No
Best for Size/color variants Engravings, gift wrap Related items sold together

Use configurable products when each variation needs its own SKU and inventory. Use custom options when you need additional choices (like gift wrapping or custom text) that do not affect inventory.

How to Get Configurable Product Options Programmatically

Method 1: Get Configurable Attributes

Retrieve the configurable attributes (size, color) and their available values:

<?php
namespace Vendor\Module\Block;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;

class ConfigOptions extends \Magento\Framework\View\Element\Template
{
    private ProductRepositoryInterface $productRepository;
    private Configurable $configurableType;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        ProductRepositoryInterface $productRepository,
        Configurable $configurableType,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        $this->configurableType = $configurableType;
        parent::__construct($context, $data);
    }

    public function getConfigurableAttributes(int $productId): array
    {
        $product = $this->productRepository->getById($productId);
        return $this->configurableType
            ->getConfigurableAttributesAsArray($product);
    }
}

This returns an array with each attribute's ID, code, label, and all available option values.

Method 2: Get Associated Simple (Child) Products

Retrieve all child products linked to a configurable parent:

public function getChildProducts(int $productId): array
{
    $product = $this->productRepository->getById($productId);
    $children = $this->configurableType
        ->getUsedProducts($product);

    $result = [];
    foreach ($children as $child) {
        $result[] = [
            'id'    => $child->getId(),
            'sku'   => $child->getSku(),
            'name'  => $child->getName(),
            'price' => $child->getPrice(),
            'stock' => $child->isSaleable(),
        ];
    }
    return $result;
}

Important: getUsedProducts() returns only saleable (in-stock, enabled) child products by default. To include out-of-stock children, set Display Out of Stock Products to Yes in Stores > Configuration > Catalog > Inventory.

Method 3: Get Options via GraphQL

For headless or PWA storefronts, use the GraphQL API:

{
  products(filter: { sku: { eq: "CONFIGURABLE-SKU" } }) {
    items {
      ... on ConfigurableProduct {
        configurable_options {
          attribute_code
          label
          values {
            value_index
            label
            swatch_data {
              value
            }
          }
        }
        variants {
          product {
            sku
            price_range {
              minimum_price {
                regular_price { value currency }
              }
            }
          }
          attributes {
            code
            label
            value_index
          }
        }
      }
    }
  }
}

This query returns both the configurable options (attributes) and all variants (child products) with their prices in a single request.

Display Configurable Options on the Category List Page

By default, Magento shows configurable product swatches on category pages. If options are not visible, follow these steps:

Step 1: Enable Swatches in Admin

  1. Go to Stores > Configuration > Catalog > Storefront
  2. Set Show Swatches in Product List to Yes
  3. Set Show Swatch Tooltip to Yes (optional)
  4. Save and flush cache

Step 2: Configure Attributes for List Display

  1. Navigate to Stores > Attributes > Product
  2. Open the attribute (e.g., Color)
  3. Under Storefront Properties, set:
    • Use in Layered Navigation = Filterable (with results)
    • Used in Product Listing = Yes
    • Used for Sorting in Product Listing = Yes (optional)
  4. Save the attribute

Step 3: Verify Attribute Input Type

Configurable attributes must use one of these input types:

Input Type Display on List Page Best For
Visual Swatch Color/image swatches Colors, patterns, textures
Text Swatch Text labels Sizes (S, M, L, XL)
Dropdown No swatches on list page Backend use only

If your attribute uses Dropdown input, customers cannot interact with it on the category page. Switch to Visual Swatch or Text Swatch for list page display.

Step 4: Clear Cache and Reindex

php bin/magento cache:flush
php bin/magento indexer:reindex catalog_product_attribute

After reindexing, visit a category page containing configurable products. Swatches should appear below each product image.

Customize the List Page Template

For advanced customization beyond swatches, modify the product list template to show configurable options as dropdowns or custom elements.

Override list.phtml in Your Theme

Create the template override:

app/design/frontend/Vendor/Theme/Magento_Catalog/templates/product/list.phtml

Inside the product loop, add logic to detect configurable products and render their options:

<?php if ($product->getTypeId() === 'configurable'): ?>
    <?php
    $typeInstance = $product->getTypeInstance();
    $attributes = $typeInstance->getConfigurableAttributesAsArray($product);
    ?>
    <div class="configurable-options-list">
        <?php foreach ($attributes as $attribute): ?>
            <div class="option-group">
                <label><?= $block->escapeHtml($attribute['label']) ?></label>
                <select name="super_attribute[<?= $block->escapeHtmlAttr($attribute['id']) ?>]">
                    <?php foreach ($attribute['values'] as $option): ?>
                        <?php if ($option['value_index']): ?>
                            <option value="<?= $block->escapeHtmlAttr($option['value_index']) ?>">
                                <?= $block->escapeHtml($option['label']) ?>
                            </option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

This code uses getConfigurableAttributesAsArray() for consistency with the programmatic examples above. The escapeHtml() and escapeHtmlAttr() calls prevent XSS vulnerabilities from user-created attribute labels.

Filter Out-of-Stock Options

Only show options that customers can purchase:

$children = $typeInstance->getUsedProducts($product);
$availableOptionIds = [];
foreach ($children as $child) {
    if ($child->isSaleable()) {
        foreach ($typeInstance->getConfigurableAttributes($product) as $attr) {
            $attrCode = $attr->getProductAttribute()->getAttributeCode();
            $availableOptionIds[$attr->getAttributeId()][] =
                $child->getData($attrCode);
        }
    }
}

Then use $availableOptionIds to skip rendering options that have zero stock.

Performance Considerations

Large catalogs with hundreds of configurable products can slow down category pages. Each configurable product requires loading its child products and attribute data.

Optimization Strategies

Strategy Impact Complexity
Varnish Full Page Cache Serves cached pages to most visitors Medium
Redis for config + page cache Reduces database load per request Medium
Limit attributes on list page Fewer queries per product Low
Lazy-load options via AJAX Loads options on hover/click, not on page load High
OpenSearch index tuning Faster attribute filtering and search Medium

Note: Avoid enabling Flat Catalog. Adobe no longer recommends it as a best practice. Flat catalogs cause indexing problems, heavy SQL load, and cron failures. Use OpenSearch/Elasticsearch with EAV instead.

Proper server infrastructure matters as much as code optimization. A store with 1,000+ configurable products and swatch images needs adequate RAM and fast disk I/O to serve category pages under 3 seconds.

Troubleshooting Common Issues

Options Not Showing on Product or List Page

Symptom Cause Fix
No swatches on category page Attribute input type is Dropdown Change to Visual Swatch or Text Swatch
Swatches visible but not clickable JavaScript error in console Check for conflicting extensions, review browser console
Options missing for specific products Child products disabled or out of stock Enable child products, check stock status
All options gone after upgrade Attribute scope changed Set attribute scope back to Global
Price doesn't update on selection JSON config not generated Run php bin/magento indexer:reindex

Wrong Price Display for Configurable Products

Magento displays the lowest child product price by default. If prices show incorrect values:

  1. Verify each child product has the correct price set
  2. Check if catalog price rules apply to child products
  3. Reindex: php bin/magento indexer:reindex catalog_product_price
  4. Flush FPC: php bin/magento cache:flush full_page

Configurable Product Not Adding to Cart from List Page

If the "Add to Cart" button fails from the category page:

  1. Ensure the form action URL includes the super_attribute parameters
  2. Check that the AJAX controller handles configurable product options
  3. Verify the product_list_toolbar block is not stripping form data
  4. Test in default Luma theme to rule out theme conflicts

SEO for Configurable Products

Search engines need clear signals about which URL to index for configurable products:

  • Canonical tags: Point all child product URLs to the parent configurable product
  • Structured data: Use Product schema with AggregateOffer for price ranges
  • Avoid indexing child products: Set simple child products to Not Visible Individually in catalog visibility
  • URL structure: Keep one clean URL per configurable product, avoid parameter-based variation URLs

This prevents duplicate content issues and consolidates link equity on the parent product page.

FAQ

What is a configurable product in Magento 2?

A configurable product is a parent product linked to multiple simple products, each representing a specific combination of attributes like size and color. The parent has no inventory. Stock is tracked at the child product level. Configurable products support Magento 2.4.8 and require attributes with Global scope.

How do I get configurable product options programmatically?

Use the getConfigurableAttributesAsArray() method from Magento\ConfigurableProduct\Model\Product\Type\Configurable. Inject this class via constructor dependency injection. Call it with the product object to receive an array of all configurable attributes and their option values.

What is the difference between configurable products and custom options?

Configurable products create separate simple products (SKUs) for each variation with individual inventory tracking. Custom options add choices to a single product without creating new SKUs. Use configurable products for size/color variants. Use custom options for add-ons like engravings or gift wrapping.

Why are configurable product options not showing on the list page?

The most common cause is the attribute input type set to Dropdown instead of Visual Swatch or Text Swatch. Go to Stores > Attributes > Product, open the attribute, and change the input type. Then flush cache and reindex with php bin/magento indexer:reindex.

How do I get child products from a configurable product?

Call $product->getTypeInstance()->getUsedProducts($product) to get an array of associated simple products. This returns only saleable children by default. To include out-of-stock products, enable Display Out of Stock Products in Stores > Configuration > Catalog > Inventory.

Can I show configurable options on the category page without extensions?

Yes. Magento supports swatches on category pages out of the box. Set the attribute input type to Visual Swatch or Text Swatch, enable Show Swatches in Product List under Stores > Configuration > Catalog > Storefront, and flush cache. No third-party extensions required for basic swatch display.

How do I handle configurable products in GraphQL?

Query using the ConfigurableProduct type with configurable_options for attributes and variants for child products. The GraphQL API returns swatch data, prices, and stock status in a single request. This approach works well for PWA Studio and headless Magento storefronts.

What causes wrong prices on configurable product pages?

Incorrect child product prices, active catalog price rules, or a stale price index cause this issue. Verify prices on each child product, check for conflicting price rules, then run php bin/magento indexer:reindex catalog_product_price and flush the full page cache.

How many configurable attributes can one product have?

Magento has no hard limit on the number of configurable attributes per product. However, each additional attribute multiplies the number of required child products. Two attributes with 5 values each create 25 children. Three attributes with 5 values each create 125 children. Keep it under 3 attributes for manageable catalog sizes.

Does server performance affect configurable product display?

Yes. Each configurable product on a category page requires loading its child products and attribute data. Category pages with 50+ configurable products generate hundreds of database queries. Managed Magento hosting with Varnish caching, Redis sessions, and adequate RAM keeps these pages fast even under traffic spikes.

Summary

Getting configurable product options in Magento 2 requires understanding both the admin configuration and the programmatic API.

For admin setup: set attribute input types to Visual Swatch or Text Swatch, enable swatches in storefront configuration, and reindex.

For code: use getConfigurableAttributesAsArray() for attributes and getUsedProducts() for child products. GraphQL provides both in a single query for headless builds.

For performance: use Varnish + Redis caching, tune OpenSearch indexes, and ensure your Magento hosting infrastructure handles the database load that configurable products create on category pages.

CEO & Co-Founder

Raphael Thiel co-founded MGT-Commerce in 2011 together with Stefan Wieczorek and has built it into a leading Magento hosting provider serving 5,000+ customers on AWS. With 25+ years in e-commerce and cloud infrastructure, he oversees hosting architecture for enterprise clients. He also co-founded CloudPanel, an open-source server management platform.


Get the fastest Magento Hosting! Get Started