如何在Prestashop 1.7商品页添加展示自定义推荐商品的新标签页
解决方案
第一步:在商品控制器中获取推荐数据
修改/controllers/front/ProductController.php,在initContent()方法内添加数据库查询逻辑,把推荐商品数据传递到模板:
// 在$this->context->smarty->assign(...)相关代码前插入 $id_product = (int)$this->product->id; $recommendations = Db::getInstance()->getRow('SELECT * FROM '._DB_PREFIX_.'recommendations WHERE id_product = '.(int)$id_product); $reco_products = []; if ($recommendations) { // 整理推荐商品ID数组,过滤无效值 $reco_ids = array_filter([ $recommendations['reco_id_1'], $recommendations['reco_id_2'], $recommendations['reco_id_3'], $recommendations['reco_id_4'] ]); // 循环获取每个推荐商品的详情 foreach ($reco_ids as $id) { $product = new Product((int)$id, false, (int)$this->context->language->id); if (Validate::isLoadedObject($product)) { $reco_products[] = $product; } } } // 将推荐商品数组传给模板 $this->context->smarty->assign('reco_products', $reco_products);
第二步:修改商品模板展示推荐内容
找到主题目录下的/templates/catalog/product.tpl,定位到商品描述下方的标签页区域,插入以下代码:
{if $reco_products} <div class="product-recommendations"> <h3>推荐商品</h3> <div class="reco-products-grid"> {foreach from=$reco_products item=reco_product} <div class="reco-product-card"> <a href="{$link->getProductLink($reco_product)}"> <img src="{$link->getImageLink($reco_product.link_rewrite, $reco_product.id_image, 'home_default')}" alt="{$reco_product.name}"> <h4>{$reco_product.name}</h4> <span class="price">{Tools::displayPrice($reco_product.price, $this->context->currency)}</span> </a> </div> {/foreach} </div> </div> {/if}
关键注意事项
- 修改核心文件前必须备份,防止操作失误导致网站异常
- 若主题有自定义商品页结构,需调整模板代码的插入位置,确保显示在目标标签页内
- 可根据主题样式,为
.product-recommendations、.reco-products-grid等类添加CSS样式,优化展示效果 - 代码中的
_DB_PREFIX_是Prestashop内置的数据库前缀常量,无需手动替换为ps_
内容的提问来源于stack exchange,提问作者Bart
相关产品推荐
相关产品推荐

