Magentoでサンプル製品カテゴリを設定して、購入ごとに最大3つの無料サンプルを選択できるようにしようとしていますが、注文ごとにそのカテゴリから3つのサンプルのみを制限するにはどうすればよいですか?
[編集]
これは、dir app / code / local / MagePal / LimitCartProductByCategory / etc/config.xml内の現在のconfig.xmlです。
<?xml version="1.0"?>
<config>
<modules>
<MagePal_LimitCartProductByCategory>
<version>1.0.1</version>
</MagePal_LimitCartProductByCategory>
</modules>
<global>
<models>
<limitcartproductbycategory>
<class>MagePal_LimitCartProductByCategory_Model_Observer</class>
</limitcartproductbycategory>
</models>
<events>
<checkout_cart_product_add_after>
<observers>
<limitcartproductbycategory>
<type>singleton</type>
<class>MagePal_LimitCartProductByCategory_Model_Observer</class>
<method>cartlimit</method>
</limitcartproductbycategory>
</observers>
</checkout_cart_product_add_after>
</events>
</global>
</config>
dir app / etc / modules / MagePal_LimitCartProductByCategory.xmlのMagePal_EnableDuplicateProductStatus.xml:
<?xml version="1.0"?>
<config>
<modules>
<MagePal_LimitCartProductByCategory>
<active>true</active>
<codePool>local</codePool>
</MagePal_LimitCartProductByCategory>
</modules>
</config>
これは、dir app / code / local / MagePal / LimitCartProductByCategory / Model/Observer.php内の現在のObserver.phpです。
class MagePal_LimitCartProductByCategory_Model_Observer
{
public function cartlimit(Varien_Event_Observer $observer)
{
$category_ids = array();
$quote = Mage::getSingleton('checkout/session')->getQuote();
foreach($quote->getAllVisibleItems() as $item){
$product = Mage::getModel('catalog/product')->load($item->getId());
$product_category_ids = explode(",", $product->getCategoryIds());
//$product_category_ids = $product->getCategoryIds();
array_push($category_ids, $product_category_ids);
}
$justAdded = $observer->getQuoteItem();
$justAddedCategoryIds = explode(",", $product->getCategoryIds());
$justAddedId = in_array(58, $justAddedCategoryIds);
$productJustAdded = Mage::getModel('catalog/product')->load($justAdded->getId());
//total the catalogegory id in $category_ids
//if $productJustAdded->getCategoryIds exist in $category_ids,
//then check to see if category id count greater than 3
// if true then add error msg and try setting the qty to 0
$freesample = 58;
$tmp = array_count_values($category_ids);
$cnt = $tmp[$freesample];
echo $cnt;
if ($justAddedId == true && $cnt > 3) {
$quote->removeItem($justAdded->getId())->save();
Mage::app()->getLayout()->getMessagesBlock()->setMessages('You can only have 3 free samples. Please remove a sample to add another.');
Mage::app()->getLayout()->getMessagesBlock()->getGroupedHtml();
}
return $this;
}
}