Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Magento auto add product custom options


// *Special note: make sure you check your sql table name, 
//  and change the option title from what i have below.

// rbanh special methods
private function rbanh_get_custom_option_id($product_id)
{
    $sql = "
        select 
            o.option_id 
        from 
            catalog_product_option o
        inner join
            catalog_product_option_title t on t.option_id = o.option_id
        where
            t.title = 'Shipping Description'
            and o.product_id = '".$product_id."'
        limit 1
            ";
    $data = Mage::getSingleton('core/resource') ->getConnection('core_read')->fetchAll($sql);
    if (count($data) > 0)
    {
        return current($data[0]);
    }
    return false;
}

// rbanh special methods
private function rbanh_add_custom_option($product_id)
{
    // make the option active
    //$write = Mage::getSingleton('core/resource')->getConnection('core_write');
    //$write->query("update catalog_product_entity set has_options = 1 where entity_id='$product_id'"); 
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');
    $sql  = "update catalog_product_entity set has_options = 1 where entity_id=?";
    $write->query($sql, $product_id); 
    
    $product = Mage::getModel('catalog/product');
    $product->load($product_id);
    $opt = Mage::getModel('catalog/product_option');
    $opt->setProduct($product);
    $option = array(
        'is_delete' => 0,
        'is_require' => false,
        'previous_group' => 'text',
        'title' => 'Shipping Description',
        'type' => 'field',
        'price_type' => 'fixed',
        'price' => '0.0000'
    );
    $opt->addOption($option);
    $opt->saveOptions();
    
    return $this->rbanh_get_custom_option_id($product_id);
}

2 responses to “Magento auto add product custom options

  1. ravi 10/04/2011 at 4:58 AM

    Very Good article

    Thanks
    JeevanSathi

  2. Jeremy DeLong 14/02/2012 at 5:03 AM

    This works Great!!!! I have spent the last 48 hours trying to get something like this to work in Magento 1.6.2, and this is the first one that actually does! I do have a question though. I have both these functions in the helper file, and then I call the second one from a observer event. Is there a way to make sure that it only runs once? I updated the product, and it re-added the custom option. I want it to only run once.

    Thanks,

    Jeremy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: