1

I'm trying to get a SKU from the first child item of a configurable product.

For a simple product, this works fine:

$product_id = Mage::registry('current_product')->getSku();

But on a configurable product I want it to show a SKU from a child product instead (need this for a remarketing add-in).

I'll end up with code something like the following - but this seems overly complex. Can this be simplified down a bit?

if($_product->getTypeId() == "configurable") {
    $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
    $simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
    $_hassku = false
    foreach($simple_collection as $simple_product){
        if($_hassku == "false") {
            echo $simple_product->getSku()
            $_hassku=="true" 
        }
    }

} else {
  $product_id = Mage::registry('current_product')->getSku();
};

If configurable, set a variable as 'false.' Do a 'foreach' - on the first one, it'll set the variable to true, and thus return only the one sku for the product.

3

Given $_product is your configurable product, use:

$_firstSimple = $_product->getTypeInstance()
    ->getUsedProductCollection()              // collection of associated products
    ->addAttributeToSelect('sku')             //  - with SKU attribute
    ->setPageSize(1)                          //  - limit to one row
    ->getFirstItem();                         //  - load and return first row
1

Interesting code. I think you can accomplish the same thing like this:

    echo(PHP_EOL.'<br>start test code');
            $cabac_childIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getChildrenIds($_product->getId(), true);
            $cabac_getSimpleId = current($cabac_childIds[0]);
            $cabac_mungo = Mage::getResourceModel('catalog/product_collection')
                                        ->addAttributeToSelect('sku')
                                        ->addIdFilter(array($cabac_getSimpleId))
                                        ;

            $product_id = $cabac_mungo->getFirstItem()->getSku() 
            echo (PHP_EOL.'<br>'.$product_id);                    
    echo(PHP_EOL.'<br>end test code');

Note that the object returned from getChildrenIds() is an array of array of simple product ids.

1

You can simplify it a little as follow.

$simpleProduct = Mage::getModel('catalog/product_type_configurable')
    ->getUsedProductCollection($_product)
    ->addAttributeToSelect('sku')
    ->addFilterByRequiredOptions()
    ->getFirstItem();

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.