PrestaShop 1.7:产品组合最低价格显示教程

PrestaShop 1.7:产品组合最低价格显示教程

本教程详细指导如何在PrestaShop 1.7中修改产品页面,使其默认显示具有最低价格的产品组合。通过覆盖ProductController中的assignAttributesGroups方法,我们可以识别并预选最低价格的变体,从而优化用户体验,确保消费者一眼就能看到产品的最优价格。文章涵盖了代码实现、Smarty模板集成及重要的开发实践。

1. 引言:PrestaShop 产品组合价格显示机制与优化需求

prestashop 默认情况下,当产品存在多种组合(如不同颜色、尺寸等)时,产品页面通常会显示默认组合的价格,或者在某些主题中,价格会根据用户选择的组合动态更新。然而,平台本身并未提供直接显示“该产品所有组合中的最低价格”的功能,也无法自动将最低价格的组合设置为默认选中状态。对于拥有大量组合商品的商家而言,这可能导致用户无法直观地看到产品的最佳性价比,从而影响转化率。

本教程旨在解决这一痛点,通过修改核心控制器逻辑,实现以下目标:

识别产品所有组合中的最低价格。将拥有最低价格的组合设置为产品页面的默认选中项。确保前端价格显示与最低价格组合保持一致。

2. 核心思路:通过控制器覆盖实现逻辑修改

PrestaShop 遵循 MVC 架构,产品页面的数据准备主要由 ProductController 负责。具体到产品组合信息的处理,assignAttributesGroups 方法是关键所在。我们将通过创建控制器覆盖(Override)来修改此方法,以避免直接修改核心文件,从而确保系统升级时的兼容性。

为什么使用覆盖?直接修改 PrestaShop 核心文件(例如 controllers/front/ProductController.php)会导致在系统更新时,您的修改被覆盖,从而丢失。使用覆盖机制 (/override 目录) 是 PrestaShop 推荐的定制方式,它允许您在不触碰核心文件的情况下扩展或修改现有功能。

3. 实现步骤:修改 ProductController

3.1 创建或修改 ProductController 覆盖文件

首先,您需要在您的 PrestaShop 安装目录中创建或修改覆盖文件。路径:your_prestashop_root/override/controllers/front/ProductController.php

如果文件不存在,请创建它。文件内容应包含以下基本结构:

<?phpclass ProductController extends ProductControllerCore{    /*     * 在这里添加或修改方法     */}

3.2 修改 assignAttributesGroups 方法

现在,我们将 assignAttributesGroups 方法复制到 ProductController.php 覆盖文件中,并进行必要的修改。我们的目标是在遍历所有属性组时,找到最低价格的组合,并将其 id_attribute 存储起来,以便后续设置为默认选中。

找到原始 assignAttributesGroups 方法中的以下代码段:

protected function assignAttributesGroups($product_for_template = null){    $colors = [];    $groups = [];    $this->combinations = [];    /** @todo (RM) should only get groups and not all declination ? */    $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);    if (is_array($attributes_groups) && $attributes_groups) {        // ... 现有逻辑 ...    }    // ... 方法的其余部分 ...}

在 $this->combinations = []; 之后,但在 /** @todo … */ 之前,添加用于查找最低价格组合的逻辑。同时,修改设置选中状态的代码,使其指向最低价格组合。

combinations = [];        // 【新增代码段1:查找最低价格组合】        $lowestPrice = ["lowest_price" => null, "lowest_price_id" => null];        $attributes_groups = $this->product->getAttributesGroups($this->context->language->id);        if (is_array($attributes_groups) && $attributes_groups) {            foreach ($attributes_groups as $k => $row) {                // 比较当前组合价格与已知的最低价格                if ($lowestPrice["lowest_price"] === null || (float)$row['price'] product->getAttributesGroups($this->context->language->id);        if (is_array($attributes_groups) && $attributes_groups) {            $combination_images = $this->product->getCombinationImages($this->context->language->id);            $combination_prices_set = [];            foreach ($attributes_groups as $k => $row) {                // Color management                if (isset($row['is_color_group']) && $row['is_color_group'] && (isset($row['attribute_color']) && $row['attribute_color']) || (file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg'))) {                    $colors[$row['id_attribute']]['value'] = $row['attribute_color'];                    $colors[$row['id_attribute']]['name'] = $row['attribute_name'];                    if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {                        $colors[$row['id_attribute']]['attributes_quantity'] = 0;                    }                    $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];                }                if (!isset($groups[$row['id_attribute_group']])) {                    $groups[$row['id_attribute_group']] = [                        'group_name' => $row['group_name'],                        'name' => $row['public_group_name'],                        'group_type' => $row['group_type'],                        'default' => -1,                    ];                }                $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = [                    'name' => $row['attribute_name'],                    'html_color_code' => $row['attribute_color'],                    'texture' => (@filemtime(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) ? _THEME_COL_DIR_ . $row['id_attribute'] . '.jpg' : '',                    // 【修改代码段2:设置选中状态】                    // 原始代码:#'selected' => (isset($product_for_template['attributes'][$row['id_attribute_group']]['id_attribute']) && $product_for_template['attributes'][$row['id_attribute_group']]['id_attribute'] == $row['id_attribute']) ? true : false,                    'selected'=> ($lowestPrice["lowest_price_id"] ==  $row['id_attribute']) ? true : false,                    // 【修改代码段2 结束】                ];                //$product.attributes.$id_attribute_group.id_attribute eq $id_attribute                if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {                    $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];                }                if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {                    $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;                }                $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];                $this->combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];                $this->combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];                $this->combinations[$row['id_product_attribute']]['price'] = (float) $row['price'];                // Call getPriceStatic in order to set $combination_specific_price                if (!isset($combination_prices_set[(int) $row['id_product_attribute']])) {                    $combination_specific_price = null;                    Product::getPriceStatic((int) $this->product->id, false, $row['id_product_attribute'], 6, null, false, true, 1, false, null, null, null, $combination_specific_price);                    $combination_prices_set[(int) $row['id_product_attribute']] = true;                    $this->combinations[$row['id_product_attribute']]['specific_price'] = $combination_specific_price;                }                $this->combinations[$row['id_product_attribute']]['ecotax'] = (float) $row['ecotax'];                $this->combinations[$row['id_product_attribute']]['weight'] = (float) $row['weight'];                $this->combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];                $this->combinations[$row['id_product_attribute']]['reference'] = $row['reference'];                $this->combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];                $this->combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];                if ($row['available_date'] != '0000-00-00' && Validate::isDate($row['available_date'])) {                    $this->combinations[$row['id_product_attribute']]['available_date'] = $row['available_date'];                    $this->combinations[$row['id_product_attribute']]['date_formatted'] = Tools::displayDate($row['available_date']);                } else {                    $this->combinations[$row['id_product_attribute']]['available_date'] = $this->combinations[$row['id_product_attribute']]['date_formatted'] = '';                }                if (!isset($combination_images[$row['id_product_attribute']][0]['id_image'])) {                    $this->combinations[$row['id_product_attribute']]['id_image'] = -1;                } else {                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $combination_images[$row['id_product_attribute']][0]['id_image'];                    if ($row['default_on']) {                        foreach ($this->context->smarty->tpl_vars['product']->value['images'] as $image) {                            if ($image['cover'] == 1) {                                $current_cover = $image;                            }                        }                        if (!isset($current_cover)) {                            $current_cover = array_values($this->context->smarty->tpl_vars['product']->value['images'])[0];                        }                        if (is_array($combination_images[$row['id_product_attribute']])) {                            foreach ($combination_images[$row['id_product_attribute']] as $tmp) {                                if ($tmp['id_image'] == $current_cover['id_image']) {                                    $this->combinations[$row['id_product_attribute']]['id_image'] = $id_image = (int) $tmp['id_image'];                                    break;                                }                            }                        }                        if ($id_image > 0) {                            if (isset($this->context->smarty->tpl_vars['images']->value)) {                                $product_images = $this->context->smarty->tpl_vars['images']->value;                            }                            if (isset($product_images) && is_array($product_images) && isset($product_images[$id_image])) {                                $product_images[$id_image]['cover'] = 1;                                $this->context->smarty->assign('mainImage', $product_images[$id_image]);                                if (count($product_images)) {                                    $this->context->smarty->assign('images', $product_images);                                }                            }                            $cover = $current_cover;                            if (isset($cover) && is_array($cover) && isset($product_images) && is_array($product_images)) {                                $product_images[$cover['id_image']]['cover'] = 0;                                if (isset($product_images[$id_image])) {                                    $cover = $product_images[$id_image];                                }                                $cover['id_image'] = (Configuration::get('PS_LEGACY_IMAGES') ? ($this->product->id . '-' . $id_image) : (int) $id_image);                                $cover['id_image_only'] = (int) $id_image;                                $this->context->smarty->assign('cover', $cover);                            }                        }                    }                }            }            // 【新增代码段3:覆盖属性组的默认选中】            // 在原始代码的 'foreach ($attributes_groups as $k => $row)' 循环结束后,            // 且在 'wash attributes list depending on available attributes' 逻辑之前添加。            // 这一步确保即使有多个属性组,也能将第一个属性组的默认选中项设置为最低价格组合的ID。            // 注意:此处的 $row['id_attribute_group'] 在循环结束后可能不是我们想要的,            // 更好的做法是遍历 $groups 数组,找到第一个属性组并设置其默认值。            // 简单起见,如果最低价格ID属于某个属性组,我们将其设置为该属性组的默认。            // 更严谨的实现需要根据 $lowestPrice['lowest_price_id'] 找到它所属的 $id_attribute_group。            // 考虑到PrestaShop通常会将所有属性归类到不同的属性组,            // 并且我们只想设置一个默认选中项,这里假设最低价格的属性ID能被正确匹配。            if ($lowestPrice["lowest_price_id"] !== null) {                foreach ($groups as $id_group => &$group_data) {                    if (isset($group_data['attributes'][$lowestPrice["lowest_price_id"]])) {                        $group_data['default'] = (int) $lowestPrice['lowest_price_id'];                        break; // 找到并设置后即可退出                    }                }            }            // 【新增代码段3 结束】            // wash attributes list depending on available attributes depending on selected preceding attributes            $current_selected_attributes = [];            $count = 0;            foreach ($groups as &$group) {                ++$count;                if ($count > 1) {                    //find attributes of current group, having a possible combination with current selected                    $id_product_attributes = [0];                    $query = 'SELECT pac.`id_product_attribute`                        FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac                        INNER JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.id_product_attribute = pac.id_product_attribute                        WHERE id_product = ' . $this->product->id . ' AND id_attribute IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')                        GROUP BY id_product_attribute                        HAVING COUNT(id_product) = ' . count($current_selected_attributes);                    if ($results = Db::getInstance()->executeS($query)) {                        foreach ($results as $row) {                            $id_product_attributes[] = $row['id_product_attribute'];                        }                    }                    $id_attributes = Db::getInstance()->executeS('SELECT `id_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute_combination` pac2                        WHERE `id_product_attribute` IN (' . implode(',', array_map('intval', $id_product_attributes)) . ')                        AND id_attribute NOT IN (' . implode(',', array_map('intval', $current_selected_attributes)) . ')');                    foreach ($id_attributes as $k => $row) {                        $id_attributes[$k] = (int) $row['id_attribute'];                    }                    foreach ($group['attributes'] as $key => $attribute) {                        if (!in_array((int) $key, $id_attributes)) {                            unset(                                $group['attributes'][$key],                                $group['attributes_quantity'][$key]                            );                        }                    }                }                //find selected attribute or first of group                $index = 0;                $current_selected_attribute = 0;                foreach ($group['attributes'] as $key => $attribute) {                    if ($index === 0) {                        $current_selected_attribute = $key;                    }                    if ($attribute['selected']) {                        $current_selected_attribute = $key;                        break;                    }                }                if ($current_selected_attribute > 0) {                    $current_selected_attributes[] = $current_selected_attribute;                }            }            // wash attributes list (if some attributes are unavailables and if allowed to wash it)            if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {                foreach ($groups as &$group) {                    foreach ($group['attributes_quantity'] as $key => &$quantity) {                        if ($quantity  $color) {                    if ($color['attributes_quantity'] combinations as $id_product_attribute => $comb) {                $attribute_list = '';                foreach ($comb['attributes'] as $id_attribute) {                    $attribute_list .= ''' . (int) $id_attribute . '',';                }                $attribute_list = rtrim($attribute_list, ',');                $this->combinations[$id_product_attribute]['list'] = $attribute_list;            }            $this->context->smarty->assign([                'groups' => $groups,                'colors' => (count($colors)) ? $colors : false,                'combinations' => $this->combinations,                'combinationImages' => $combination_images,            ]);        } else {            $this->context->smarty->assign([                'groups' => [],                'colors' => false,                'combinations' => [],                'combination

以上就是PrestaShop 1.7:产品组合最低价格显示教程的详细内容,更多请关注php中文网其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1273197.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
php如何处理JSON中的Unicode字符?PHP JSON Unicode字符处理方法
上一篇 2025年12月10日 15:28:31
php抽象类和接口有什么区别?PHP抽象类与接口对比分析
下一篇 2025年12月10日 15:28:40

相关推荐

  • composer require-dev和require有什么不同_Composer Require与Require-Dev区别解析

    require用于声明项目运行必需的依赖,如框架、数据库组件和第三方SDK,这些包会随项目部署到生产环境;2. require-dev用于声明仅在开发和测试阶段需要的工具,如PHPUnit、PHPStan、Faker等,不会默认部署到生产环境;3. 安装时composer install根据环境决定…

    2026年5月10日
    1000
  • 修复Django电商项目中AJAX过滤产品列表图片不显示问题

    在Django电商项目中,当使用AJAX动态加载过滤后的产品列表时,常遇到图片无法正常显示的问题。这通常是由于前端模板中图片加载方式(如data-setbg属性结合JavaScript库)与AJAX动态内容更新机制不兼容所致。解决方案是直接在AJAX返回的HTML中使用标准的标签来渲染图片,确保浏览…

    2026年5月10日
    000
  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    000
  • 怎么在PHP代码中实现图片上传功能_PHP图片上传功能实现与安全处理教程

    首先创建含enctype的HTML表单,再用PHP接收文件,检查目录、移动临时文件,验证类型与大小,生成唯一文件名,并调整php.ini限制以确保上传成功。 如果您尝试在PHP项目中添加图片上传功能,但服务器无法正确接收或保存文件,则可能是由于表单配置、文件处理逻辑或安全限制的问题。以下是实现该功能…

    2026年5月10日
    100
  • 获取日期中的周数:CodeIgniter 教程

    本教程旨在帮助开发者在 CodeIgniter 框架中,从日期字符串中准确提取周数。我们将使用 PHP 内置的 DateTime 类,并提供详细的代码示例和注意事项,确保您能够轻松地在项目中实现此功能。 使用 DateTime 类获取周数 PHP 的 DateTime 类提供了一种便捷的方式来处理日…

    2026年5月10日
    100
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • HTML如何隐藏滚动条或去除滚动条

    滚动条可以存在也可以不存在,本文主要介绍了html 隐藏滚动条和去除滚动条的方法的相关资料,大家一起来学习一下html隐藏滚动条或去除滚动条的方法吧。 1. html 标签加属性 XML/HTML Code复制内容到剪贴板 2.body中加入以下代码 立即学习“前端免费学习笔记(深入)”; html…

    用户投稿 2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • vscode上怎么运行html_vscode上运行html步骤【指南】

    首先保存文件为.html格式,再通过浏览器或Live Server插件打开预览;推荐安装Live Server实现本地服务器运行与实时刷新,提升开发体验。 在 VS Code 上运行 HTML 文件并不需要复杂的配置,只需几个简单步骤即可预览页面效果。VS Code 本身是一个代码编辑器,不直接运行…

    2026年5月10日
    100
  • 修复点击时按钮抖动:CSS垂直对齐实践

    本文探讨了在Web开发中,交互式按钮(如播放/暂停按钮)在点击时发生意外垂直位移的问题。通过分析CSS样式变化对元素布局的影响,我们发现这是由于按钮不同状态下的边框样式和内边距改变,以及默认的垂直对齐行为共同作用所致。核心解决方案是利用CSS的vertical-align属性,将其设置为middle…

    2026年5月10日
    100
  • 理解编程指令:当结果正确,但实现方式不符要求时

    本文探讨了在编程实践中,即使程序输出了正确的结果,但若其实现方式未能严格遵循既定指令,仍可能被视为“不正确”的问题。我们将通过具体示例,对比直接求和与累加求和两种实现策略,强调理解和遵守编程规范的重要性,以确保代码的健壮性、可维护性及符合项目要求。 在软件开发过程中,我们经常会遇到这样的情况:编写的…

    2026年5月10日
    000
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 页面中文本域的值怎么设置

    标签定义多行的文本输入控件。 文本区中可容纳无限数量的文本,其中的文本的默认字体是等宽字体(通常是 Courier)。 可以通过 cols 和 rows 属性来规定 textarea 的尺寸,不过更好的办法是使用 CSS 的 height 和 width 属性。 注释:在文本输入区内的文本行间,用 …

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    200
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • php常量怎么用_PHP常量(define/const)定义与使用方法

    PHP中可通过define函数和const关键字定义常量,用于存储不可变值。define适用于全局作用域,支持动态名称和条件定义,如define(‘SITE_NAME’, ‘MyWebsite’);const在编译时生效,语法简洁但限制多,只能在类或全…

    2026年5月10日
    000
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    100
  • 前端缓存策略与JavaScript存储管理

    根据数据特性选择合适的存储方式并制定清晰的读写与清理逻辑,能显著提升前端性能;合理运用Cookie、localStorage、sessionStorage、IndexedDB及Cache API,结合缓存策略与定期清理机制,可在保证用户体验的同时避免安全与性能隐患。 前端缓存和JavaScript存…

    2026年5月10日
    200

发表回复

登录后才能评论
关注微信