How to get configurable product’s used super_attribute details programmatically in Magento 2?

We can get the details of the used super attribute value for the configurable product. You will get the attribute value used in the configurable product using the below example.

Let’s assume a configurable product generated with color and size attributes. But how we can get details of super attribute value using a programmatic way that product is made using color or size or color and size or any other attributes combination.

You can retrieve the Child Product Used Super attribute details for the configurable product.

We can get Dynamically Configurable Product’s used Super attribute details by below code snippet.

<?php
namespace Rbj\ConfigProduct\Block;

class SuperAttribute
{
    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    /**
     * get Super Attribute details by configurable product id
     */
    public function getSuperAttributeData($productId);
    {
        /** @var \Magento\Catalog\Model\Product $product */
        $product = $this->productRepository->getById($id);
        if ($product->getTypeId() != \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
            return [];
        }

        /** @var \Magento\ConfigurableProduct\Model\Product\Type\Configurable $productTypeInstance */
        $productTypeInstance = $product->getTypeInstance();
        $productTypeInstance->setStoreFilter($product->getStoreId(), $product);

        $attributes = $productTypeInstance->getConfigurableAttributes($product);
        $superAttributeList = [];
        foreach($attributes as $_attribute){
            $attributeCode = $_attribute->getProductAttribute()->getAttributeCode();;
            $superAttributeList[$_attribute->getAttributeId()] = $attributeCode;
        }
        return $superAttributeList;
    }

Call function from a PHP class file,

$productId = 67;
$superAttribute = $this->getSuperAttributeData($productId);
echo "<pre>";print_r($superAttribute);

The result will be,

Array
(
   [93] => color
   [254] => size
)

Where 93,254 are attribute id and color, size is attribute code. Based on output we can say a configurable product is made using color and size super attribute.