$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Catalog\Model\Product')->load('YOUR PRODUCT ID');
echo $product->getAttributeText('your_attribut');

I need to get product in carts with custom attribute values to pass in a XML for a API POST call I am making.

Say I dont have the product ID, and I just want to get the product in cart with custom attribute value, how would I do that?


You can get it like below:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->get('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productCollection->addAttributeToFilter('your_attribut', 'your_value');

You got the collection. Now you can look through and get what you need. you can also set attribute to select like this:


This is just to explain. In real implementation you should not directly use the ObjectManager but use constructor injection for using the Product Model.

  • yes, I know and I already suggested if you read the complete answer that I have written but I don't know how and where it needs to be implemented so just explained using the same pattern – Arif Ahmad May 29 '19 at 4:03

If you want to get custom attribute value of product collection.

$products = $obj->get('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create()->addAttributeToSelect('*')->setPageSize(20);
echo '<pre>';
echo count($products);
foreach ($products as $product) {
// print_r($product->getData());
echo $product->getDisplayFlag();
echo '</pre>';

And If you know the product id and want to get custom attribute value.

$product = $obj->get('Magento\Catalog\Model\Product')->load(8041);
echo $product->getCustomAttribute('display_flag')->getValue();
//echo $product->getDisplayFlag();

Get Product custom attribute by product id

here, below code "battery_type" is my custom multiselect attribute. foreach loop used for mutiple value if selected in this attribute field so last coma (,) removed using for each loop.

$productId = "2"; //Product Id

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);

    echo $product->getName()."<br>"; 
    echo $product->getPrice()."<br>";
    $battery_type = $product->getAttributeText('battery_type');

$s = '';
$n = count($battery_type);
foreach ($battery_type as $i => $result) { 
    $s .= $result;
    if (($i+1) != $n) $s .= ' , ';
echo $s;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.