第 1 步:创建 Events/xml文件
首先,您需要events/xml在文件夹中创建Webkul/Hello/etc/frontend并使用事件checkout_cart_product_add_after
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_product_add_after">
<observer name="customprice" instance="Webkul\Hello\Observer\CustomPrice" />
</event>
</config>
第 2 步:创建 CustomPrice.php 文件
现在,您必须在文件夹中创建CustomPrice.php覆盖您的价格的Observer文件。
<?php
/**
* Webkul Hello CustomPrice Observer
*
* @category Webkul
* @package Webkul_Hello
* @author Webkul Software Private Limited
*
*/
namespace Webkul\Hello\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
class CustomPrice implements ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer) {
$item = $observer->getEvent()->getData('quote_item');
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
$price = 100; //set your price here
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}
}
注意:根据您需要为一种或多种产品设置自定义价格,您可以通过添加条件来进行操作。