购物车商品价格计算,基于 Woocommerce 中选择的“天”自定义字段

2024-03-11

在 Woocommerce 中,我根据以下线程代码使用自定义字段来计算产品的价格:在 Woocommerce 3 中将产品自定义字段显示为订单项目 https://stackoverflow.com/questions/52014275/display-product-custom-fields-as-order-items-in-woocommerce-3.

// Add a custom field before single add to cart
add_action('woocommerce_before_add_to_cart_button', 'custom_product_price_field', 5);

function custom_product_price_field() {
echo '<div class="custom-text text">
<h3>Rental</h3>
<label>Start Date:</label>
<input type="date" name="rental_date" value="" class="rental_date" />
<label>Period Rental:</label>
<select name="custom_price" class="custom_price">
    <option value="" selected="selected">choosen period</option>
    <option value="2">2 days</option>
    <option value="4">4 days</option>
</select>
</div>';
}

// Get custom field value, calculate new item price, save it as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 3);

function add_custom_field_data($cart_item_data, $product_id, $variation_id) {
if (isset($_POST['rental_date']) && !empty($_POST['rental_date'])) {
        $cart_item_data['custom_data']['date'] = $_POST['rental_date'];
}
if (isset($_POST['custom_price']) && !empty($_POST['custom_price'])) {
        $_product_id = $variation_id > 0 ? $variation_id : $product_id;
        $product = wc_get_product($_product_id); // The WC_Product Object
        $base_price = (float) $product - > get_regular_price(); // Product reg price
        $custom_price = (float) sanitize_text_field($_POST['custom_price']);

        $cart_item_data['custom_data']['base_price'] = $base_price;
        $cart_item_data['custom_data']['new_price'] = $base_price/100 * 15 * $custom_price;
        $cart_item_data['custom_data']['rental'] = $custom_price;
}
if (isset($cart_item_data['custom_data']['new_price']) || isset($cart_item_data['custom_data']['date'])) {
        $cart_item_data['custom_data']['unique_key'] = md5(microtime().rand()); // Make each item unique
}
return $cart_item_data;
}

// Set the new calculated cart item price
add_action('woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1);

function extra_price_add_custom_price($cart) {
if (is_admin() && !defined('DOING_AJAX'))
        return;

foreach($cart - > get_cart() as $cart_item) {
        if (isset($cart_item['custom_data']['new_price']))
                $cart_item['data'] - > set_price((float) $cart_item['custom_data']['new_price']);
}
}

// Display cart item custom price details
add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3);

function display_cart_items_custom_price_details($product_price, $cart_item, $cart_item_key) {
if (isset($cart_item['custom_data']['base_price'])) {
        $product = $cart_item['data'];
        $base_price = $cart_item['custom_data']['base_price'];
        $product_price = wc_price(wc_get_price_to_display($product, array('price' => $base_price))).
        '<br>';
        if (isset($cart_item['custom_data']['rental'])) {
                $product_price. = $cart_item['custom_data']['rental'] == '2' ? __("2 days") : __("4 days");
        }
}
return $product_price;
}

// Display in cart item the selected date
add_filter('woocommerce_get_item_data', 'display_custom_item_data', 10, 2);

function display_custom_item_data($cart_item_data, $cart_item) {
if (isset($cart_item['custom_data']['date'])) {

        $cart_item_data[] = array(
                'name' => __("Chosen date", "woocommerce"),
                'value' => date('d.m.Y', strtotime($cart_item['custom_data']['date'])),
        );
}
if (isset($cart_item['custom_data']['rental'])) {
        $cart_item_data[] = array(
                'name' => __("Period Rental", "woocommerce"),
                'value' => $cart_item['custom_data']['rental'] == '2' ? __("2 days") : __("4 days"),
        );
}
return $cart_item_data;
}

有必要改变计算新价格的条件。目前,新价格的计算不考虑天数。这是必要条件。

如果用户选择“2天”,那么计算将是...$base_price/100 * 15 * value=2

如果用户选择“4天”,那么计算将是...$base_price/100 * 15 * value=4

我怎样才能做到这一点?

UPDATE:抱歉,忘记添加您给我的最后一个代码。怎样才能和他在一起呢?

// Save and display custom field in orders and email notifications (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_fields_update_order_item_meta', 20, 4 );
function custom_fields_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
if ( isset( $values['custom_data']['date'] ) ){
    $date = date( 'd.m.Y', strtotime( $values['custom_data']['date'] ) );
    $item->update_meta_data( __( 'Choosen Date', 'woocommerce' ), $date );
}
if ( isset( $values['custom_data']['rental'] ) ){
    $rental = $values['custom_data']['rental'] == '2' ? __("2 days") : __("4 days");
    $item->update_meta_data( __( 'Period Rental', 'woocommerce' ), $rental );
}
}

您问题中的代码出错由于代码格式的原因,当然是在复制粘贴时。
例如- >需要-> or $product_price. =需要$product_price .=
要了解,请参阅PHP 运算符 http://php.net/manual/en/language.operators.php.

下面您将找到根据租金“期限”进行计算的正确方法(days):

// HERE your rental days settings
function get_rental_days_options() {
    return array(
        '2' => __("2 Days", "woocommerce"),
        '4' => __("4 Days", "woocommerce"),
    );
}

// Add a custom field before single add to cart
add_action('woocommerce_before_add_to_cart_button', 'display_single_product_custom_fields', 5);

function display_single_product_custom_fields() {
    // Get the rental days data options
    $options = array(''  => __("Choosen period", "woocommerce")) + get_rental_days_options();

    echo '<div class="custom-text text">
    <h3>'.__("Rental", "woocommerce").'</h3>
    <label>'.__("Start Date", "woocommerce").': </label>
    <input type="date" name="rental_date" value="" class="rental_date" />
    <label>Period:</label>
    <select class="rental-days" id="rental-days" name="rental_days">';

    foreach( $options as $key => $option ){
        echo '<option value="'.$key.'">'.$option.'</option>';
    }

    echo '</select>
    </div>';
}

// Get custom field value, calculate new item price, save it as custom cart item data
add_filter('woocommerce_add_cart_item_data', 'add_custom_field_data', 20, 3);

function add_custom_field_data($cart_item_data, $product_id, $variation_id) {
    // HERE set the percentage rate to be applied to get the new price
    $percentage  = 2;

    if (isset($_POST['rental_date']) && !empty($_POST['rental_date'])) {
        $cart_item_data['custom_data']['start_date'] = $_POST['rental_date'];
    }

    if (isset($_POST['rental_days']) && !empty($_POST['rental_days'])) {
        $cart_item_data['custom_data']['rental_days'] = esc_attr($_POST['rental_days']);

        $_product_id = $variation_id > 0 ? $variation_id : $product_id;

        $product     = wc_get_product($_product_id); // The WC_Product Object
        $base_price  = (float) $product->get_regular_price(); // Get the product regular price

        $price_rate  = $cart_item_data['custom_data']['rental_days'] * $percentage / 100;

        $cart_item_data['custom_data']['base_price']  = $base_price;
        $cart_item_data['custom_data']['new_price']   = $base_price * $price_rate;
    }

    // Make each cart item unique
    if (isset($cart_item_data['custom_data']['rental_days']) || isset($cart_item_data['custom_data']['start_date'])) {
        $cart_item_data['custom_data']['unique_key'] = md5(microtime().rand());
    }

    return $cart_item_data;
}

// Set the new calculated cart item price
add_action('woocommerce_before_calculate_totals', 'extra_price_add_custom_price', 20, 1);
function extra_price_add_custom_price($cart) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    foreach($cart->get_cart() as $cart_item) {
        if (isset($cart_item['custom_data']['new_price']))
            $cart_item['data']->set_price((float) $cart_item['custom_data']['new_price']);
    }
}

// Display cart item custom price details
add_filter('woocommerce_cart_item_price', 'display_cart_items_custom_price_details', 20, 3);

function display_cart_items_custom_price_details($product_price, $cart_item, $cart_item_key) {
    if (isset($cart_item['custom_data']['base_price'])) {
        $product = $cart_item['data'];
        $base_price = $cart_item['custom_data']['base_price'];
        $product_price = wc_price(wc_get_price_to_display($product, array('price' => $base_price))). '<br>';

        if (isset($cart_item['custom_data']['rental_days'])) {
            $rental_days    = get_rental_days_options();
            $product_price .= $rental_days[$cart_item['custom_data']['rental_days']];
        }
    }
    return $product_price;
}

// Display in cart item the selected date
add_filter('woocommerce_get_item_data', 'display_custom_item_data', 10, 2);

function display_custom_item_data($cart_item_data, $cart_item) {
    if (isset($cart_item['custom_data']['start_date'])) {
        $cart_item_data[] = array(
            'name'  => __("Rental start date", "woocommerce"),
            'value' => date('d.m.Y', strtotime($cart_item['custom_data']['start_date'])),
        );
    }

    if (isset($cart_item['custom_data']['rental_days'])) {
        $rental_days    = get_rental_days_options();
        $cart_item_data[] = array(
            'name'  => __("Rental period", "woocommerce"),
            'value' => $rental_days[$cart_item['custom_data']['rental_days']],
        );
    }

    return $cart_item_data;
}

// Save and display custom field in orders and email notifications (everywhere)
add_action( 'woocommerce_checkout_create_order_line_item', 'custom_fields_update_order_item_meta', 20, 4 );

function custom_fields_update_order_item_meta( $item, $cart_item_key, $values, $order ) {
    if ( isset( $values['custom_data']['date'] ) ){
        $date = date( 'd.m.Y', strtotime( $values['custom_data']['date'] ) );
        $item->update_meta_data( __( 'Start date', 'woocommerce' ), $date );
    }
    if ( isset( $values['custom_data']['rental_days'] ) ){
        $rental_days = get_rental_days_options();
        $item->update_meta_data( __( 'Rental period', 'woocommerce' ), $rental_days[$values['custom_data']['rental_days']] );
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

购物车商品价格计算,基于 Woocommerce 中选择的“天”自定义字段 的相关文章

  • 如何用php检测浏览器是否是firefox? [复制]

    这个问题在这里已经有答案了 可能的重复 有没有php代码可以检测浏览器的版本和操作系统 https stackoverflow com questions 2142030 any php code to detect the browser
  • PHP 5.3 中可以使用 new 作为方法名称吗?

    我很嫉妒 Ruby 使用 new 作为方法 在 PHP 5 3 中是否可以使用命名空间来实现这一点 class Foo public function new echo Hello 如你看到的here http php net manual
  • 为什么 MySQLi 库本身不支持命名参数?

    正确的 MySQLi 参数化查询语法来自http php net manual en mysqli quickstart prepared statements php http php net manual en mysqli quick
  • PHP实现的机票预订系统

    如何防止预订系统中的座位被重复预订 我正在用 PHP 和 MYSQL 制作一个航空旅行预订系统模型作为一个项目 我有一个小问题 仅在付款后 门票和座位详细信息才会永久存储在此处 座位号在付款前分配 假设人 1 预订了飞机上的座位 x 并支付
  • PHP MySQL 查询带有 %s 和 %d

    SELECT COUNT AS test FROM s WHERE id d AND tmp mail lt gt 什么是 s and d for 这些是使用的格式符号 例如经过sprintf 例子 Output SELECT COUNT
  • 如何在 Laravel 5 中通过键获取所有缓存项的列表?

    Laravel 中的 Cache 类具有 get itemKey 等方法来从缓存中检索项目 以及 Remember itemKey myData1 myData2 来将项目保存在缓存中 还有一个方法可以检查缓存中是否存在某个项目 Cache
  • PHP curl exec 在 php 脚本相同域上失败

    我使用 php curl 从同一域 url 中的 php 脚本获取内容 但我收到curl exec 错误 curl 错误代码为 28 或操作超时 经过几天的调试 我发现它可以在 htm 等非脚本页面上工作 但不能在 php 上工作 如果 u
  • Symfony 3新建项目报错

    我开始编写有关 Symfony 3 的教程 在使用以下命令创建新项目时遇到问题 php symfony phar new Symfony 我有这个错误 GuzzleHttp Exception RequestException Error
  • mysqli::real_connect 和 new mysqli 对象在连接数据库方面有什么区别?

    我正在使用这种方法连接到mysql db this gt Con new mysqli this gt DB Server this gt DB User this gt DB Pass this gt DB DB 当我使用这种方法连接时有
  • Woocommerce 中的欧洲 GDPR 附加结帐验证复选框

    您好 我一直在尝试向我的 Woocommerce 结帐页面添加一个额外的条件复选框 该复选框与条款和条件相同 但包含有关新 GDPR 数据保护 的信息以及指向我的隐私政策的链接 他们必须在方框中打勾才能结帐 我一直在使用从此处找到的各种代码
  • PHP file_exists() 对我不起作用?

    由于某种原因 下面的 PHP 代码将无法工作 我无法弄清楚 很奇怪的是 file exists 似乎没有看到图像确实存在 我已经检查以确保将良好的文件路径插入到 file exists 函数中并且它仍在运行 如果我将 file exists
  • 多文件上传字段的重力形式预览缩略图

    我们使用重力形式将多个图像附加到图库自定义字段并创建新帖子 我们不知道如何在 HTML5 导入字段下显示图像缩略图 而不仅仅是在提交表单之前显示文件名 之前的答案仅涵盖单个文件上传 图片上传重力形式预览 https stackoverflo
  • MYSQL:SQL查询获取自增字段的值

    我有一张桌子 主键是id及其自动递增 现在 当我插入新记录时 我需要获取更新记录的 id 我怎样才能做到这一点 如果我使用查询 select max id from table name 执行后我可以获得id 但我能确定它是刚刚插入的记录的
  • Mysql获取特定表的最后一个id

    我必须从特定的插入表中获取最后的插入 ID 可以说我有这个代码 INSERT INTO blahblah test1 test 2 VALUES test1 test2 INSERT INTO blahblah2 test1 test 2
  • 在 JQuery ui 自动完成中显示图像

    我有一个带有 JQuery ui 自动完成功能的脚本 可以完美运行 有一个显示用户名字和姓氏的搜索过程 但在我的数据库中 还有用户的图片 我想将其显示在带有名字和姓氏的建议中 数据库中pic包含图片url 剧本 function searc
  • 具有挑战性的问题 - 使用 PHP 对 XML 数据进行排序

    我有 xml 文件 其中包含大量产品数据 我需要根据我的字段 ProductRange 的数据对我的产品进行排序 ProductRange urldecode GET Range XML 文件数据
  • PHP 启动:无法加载动态库 php5.4.3/ext/php_ffmpeg.dll 不是有效的 Win32 应用程序

    再会 我尝试在 Windows 7 计算机上安装 dll 文件 php ffmpeg 但不断收到此错误 29 Jan 2013 11 37 00 UTC PHP Warning PHP Startup Unable to load dyna
  • 在 PHP 中设置 HTTP 响应代码(在 Apache 下)

    给出以下两种在 PHP 中设置 HTTP 响应代码的方法 具体来说 在 Apache 下 方法一 http response code 404 方法二 header HTTP 1 0 404 Not Found 我的问题是 除了这个事实之外
  • 间歇性 PHP 抽象类错误

    我已经为此奋斗了一段时间 但无法弄清楚 也许其他人也有 或者 Slim PHP Apache 等这里有更深层次的问题 在正常工作几个小时后 我的 Slim 安装将开始给出所有路线均如此 致命错误 类 Slim Collection 包含 1
  • 纯旧 PHP 对象 (POPO) 一词的确切含义是什么?

    我想了解一下波波 我搜索了 popo 发现它代表 Plain Old Php Object 但我不确定 Plain Old Php Object 的确切含义 我想知道什么是 popo 以及在哪里使用它 谢谢 普通旧 在此处插入语言 对象是一

随机推荐