Magento2 Custom Attributes – Get Product Attributes at Root

custom-attributesmagento-2.1magento2productproduct-attribute

I need to get values from some custom attributes from products. I'm using separate php file outside Magento folder and I'm using mostly $shippingRates to get the information I need.

I need to first load the product from SKU. I got SKU from Order.as follows,

$orderObj = $objectManager->create('Magento\Sales\Model\Order')->load($orderID);
$items =$orderObj->getAllVisibleItems();
foreach($items as $item):
$itemSku = $item->getSku();
endforeach;

I need to filter the product by SKU to get only needed products.
But the way I did wasn't a success.

So I tried loading products separately.

I loaded product using ProductRepository and Product Model,

$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

and

$getProduct = $objectManager->get('\Magento\Catalog\Model\Product');

I tried to filter product loading by sku as follows,

$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
$skuLoopProd = $item->getSku();
$getProduct = $productRepository->get($skuLoopProd);

And I tried as follows to get custom attribute value,

$axs = $getProduct->getResource()->getAttribute('product_weight_class')->getOptions();
foreach ($axs as $keyAttr) {
echo $keyAttr->getLabel();
}

but in this, I got all available options for the attribute, not the attribute value applied to the product.

What was wrong with what I tried so far?

Can please someone help me to get text value from a custom attribute of a product that I can filter with SKU?

Best Answer

First get the product ID using Product Repository and Object manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

// Get the Product Repository
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');

// Get the Product Id using sku
$product = $productRepository->get($productSku);

// Create the product object using product ID
$product = $productRepository->getById( $product->getId());

// Call the Attributes 
$product->getData('product_weight_class');
or
$product->getAttributeText('product_weight_class');

Try this and update.

Related Topic