You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Magento 1.9中指定特定店铺ID添加商品到购物车?

Magento 1.9 向指定店铺购物车添加商品的修正方案

你的代码无效的核心原因是:checkout/cart 实例依赖于当前店铺的会话环境,仅给cart对象设置storeId无法切换其关联的会话上下文,必须先切换全局店铺环境,再初始化对应店铺的购物车。

以下是修正后的代码:

// 保存当前店铺ID,避免影响后续业务逻辑
$currentStoreId = Mage::app()->getStore()->getId();

try {
    // 切换到目标店铺(ID为8)
    Mage::app()->setCurrentStore(8);
    
    // 初始化目标店铺的购物车会话
    $cart = Mage::getSingleton('checkout/cart');
    $cart->init();
    
    // 添加商品到购物车
    $product = Mage::getModel('catalog/product')->load($productId);
    if ($product->getId()) {
        $cart->addProduct($product, array('qty' => $qty));
        $cart->save();
        Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    }
} catch (Exception $e) {
    // 捕获异常并处理,比如记录日志
    Mage::log($e->getMessage(), null, 'add_to_cart_error.log');
} finally {
    // 恢复原来的店铺环境
    Mage::app()->setCurrentStore($currentStoreId);
}

关键说明:

  • 必须通过Mage::app()->setCurrentStore()切换全局店铺,这样checkout会话才会关联到目标店铺的购物车
  • 添加商品前先加载商品模型,确保商品在目标店铺中可见(避免商品未分配到该店铺导致添加失败)
  • 使用try-finally结构保证无论操作成功与否,都会恢复原店铺环境,防止影响后续业务

内容的提问来源于stack exchange,提问作者Jpenailillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:50:57