I have fetched options attribute value as

<?php $packaging = $_product->getResource()->getAttribute('packaging')->getFrontend()->getValue($_product);?>  

I am getting options value, I am trying to fetch option id as per value. I tried but its not working

if ($packaging->usesSource()) {$option_id = $packaging->getSource()->getOptionId($packaging); } 
有帮助吗?

解决方案

You have defined $attr instead of $packaging in your code.

<?php 
    $packaging =$_product->getResource()->getAttribute('packaging')->getFrontend()->getValue($_product);?>  

    $attributeExist =$_product->getResource()->getAttribute('packaging');

    if ($attributeExist->usesSource()) {
        echo $option_id = $attributeExist->getSource()->getOptionId($packaging); 
    } 
    ?>

其他提示

This works for me

<?php foreach($product->getResource()->getAttribute('color')->getSource()->getAllOptions() as $ak=>$av): ?>
            <?php if (strtolower($av['label']) == strtolower($product->getAttributeText('color'))):?>
            <p>id: <?= $av['value']?></p>
            <?php endif;?>
        <?php endforeach; ?>

For each product I am checking if it matches then I get the id of the product if there are not checks it will display all possible colours variation for that product it that is what you want.

Cheers

许可以下: CC-BY-SA归因
scroll top