如何在PrestaShop 1.7多店模式的自定义模块及产品卡片页获取商店列表
PrestaShop 1.7 多店模式开发问题解答
1. 开发自定义模块时获取所有商店列表
PrestaShop 核心内置的Shop类提供了原生方法直接读取全量商店数据,无需自定义数据库查询:
- 基础调用方式:
\Shop::getShops(),默认返回所有已激活商店的二维数组,每个元素包含id_shop、name、domain、uri等核心字段 - 如果需要获取包含未激活的商店,可传入参数
true:\Shop::getShops(true) - 示例代码:
// 模块内调用示例 public function getShopOptions() { $shops = \Shop::getShops(); $options = []; foreach ($shops as $shop) { $options[$shop['id_shop']] = $shop['name']; } return $options; }
注意:即使站点未开启多店模式,该方法也会正常返回默认商店的单条数据,无需额外做兼容判断。
2. 产品卡片页面拉取多店体系下的全部商店列表
分后台、前台两种场景处理:
后台产品卡片/编辑页
PrestaShop 后台的产品控制器默认已经注入了全商店数据到模板上下文,两种实现方式:
- 逻辑层直接调用和上述相同的
\Shop::getShops()方法读取数据 - Twig模板内直接用内置变量
{{ shops }}遍历输出即可
前台产品卡片/详情页
需要先把商店数据赋值到模板变量,再在前端渲染,示例流程:
- 在自定义模块中注册产品页相关钩子(如
displayProductButtons、displayProductAdditionalInfo等) - 在钩子方法中拉取商店列表并赋值给模板
// 模块主文件钩子实现 public function hookDisplayProductAdditionalInfo($params) { // 拉取全商店列表 $allShops = \Shop::getShops(); // 拉取当前产品关联的商店ID(可选,用于过滤仅展示产品上架的商店) $productShopIds = \Product::getShopIds($params['product']->id); $this->context->smarty->assign([ 'all_shops' => $allShops, 'product_shop_ids' => $productShopIds, 'current_product' => $params['product'] ]); return $this->display(__FILE__, 'views/templates/front/product_shop_list.tpl'); }
- 在对应模板文件中渲染列表:
{* product_shop_list.tpl 示例代码 *} {if $all_shops|count > 1} <div class="product-multishop-list"> <h4>本产品同步在售站点:</h4> <ul> {foreach from=$all_shops item=shop} {* 可选过滤:仅展示当前产品上架的商店 *} {if in_array($shop.id_shop, $product_shop_ids)} <li> <a href="//{$shop.domain}{$shop.uri}p/{$current_product.id}-{$current_product.link_rewrite}.html" target="_blank"> {$shop.name} </a> </li> {/if} {/foreach} </ul> </div> {/if}
内容的提问来源于stack exchange,提问作者webgrig
相关产品推荐
相关产品推荐

