php - 在 WooCommerce 中根据数量显示产品价格
问题描述
如何在 woocommerce 商店页面中显示基于 12 个数量的产品价格。
function sv_change_product_html( $price_html, $product ) {
$unit_price = get_post_meta( $product->id, 'unit_price', true );
if ( ! empty( $unit_price ) ) {
$price_html = '<span class="amount">' . wc_price( $unit_price ) . ' inc GST per bottle</span>';
}
return $price_html;
}
add_filter( 'woocommerce_get_price_html', 'sv_change_product_html', 10, 2 );
function sv_change_product_price_cart( $price, $cart_item, $cart_item_key ) {
$unit_price = get_post_meta( $cart_item['product_id'], 'unit_price', true );
if ( ! empty( $unit_price ) ) {
$price = wc_price( $unit_price ) . ' inc GST per bottle';
}
return $price;
}
add_filter( 'woocommerce_cart_item_price', 'sv_change_product_price_cart', 10, 3 );
解决方案
自 WooCommerce 3 以来,您的代码有点过时(而且您的问题有点不清楚)......尝试以下操作:
add_filter( 'woocommerce_get_price_html', 'displayed_product_unit_price', 10, 2 );
function displayed_product_unit_price( $price_html, $product ) {
if ( $unit_price = $product->get_meta( 'unit_price' ) ) {
$price_html = '<span class="amount">' . wc_price( floatval( $unit_price ) ) . ' ' . __( "inc GST per bottle", "woocommerce") . '</span><br>';
$price_html .= '<span class="amount">' . wc_price( floatval( $unit_price ) * 12 ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';
}
return $price_html;
}
add_filter( 'woocommerce_cart_item_price', 'displayed_cart_item_unit_price', 10, 3 );
function displayed_cart_item_unit_price( $price, $cart_item, $cart_item_key ) {
if ( $unit_price = $cart_item['data']->get_meta( 'unit_price' ) ) {
$price = wc_price( floatval( $unit_price ) ) . ' ' . __( "inc GST per bottle", "woocommerce");
}
return $price;
}
代码位于您的活动子主题(或活动主题)的 function.php 文件中。它应该有效。
现在,如果 WooCommerce 产品有效价格(默认)基于 12 瓶,您应该替换以下行(在第一个函数中):
$price_html .= '<span class="amount">' . wc_price( floatval( $unit_price ) * 12 ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';
通过这一行:
$price_html .= '<span class="amount">' . wc_price( wc_get_price_to_display( $product ) ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';
推荐阅读
- javascript - javascript require 来自 npm 的包返回 1
- laravel - 如何在laravel中加入三个表
- python - 我一直在尝试在 python 中制作一个聊天机器人,但是在密码检索过程中它不断循环密码输入语句。有解决办法吗?
- node.js - 使用 aes-128-ecb 的 AES 解密问题
- spring-boot - 具有 1 个密钥或多个密钥的 Kafka Streams 性能
- css - Bootstrap Navbar 与其他框架
- mysql - 如何根据其他两个表中定义的关系内部连接两个表
- android - android studio 模拟器不工作(无法将属性“qemu.gles”设置为“1”)
- php - 以指定模式对自定义帖子类型进行分页
- android - 用户成功注册时再创建两个用户 - Firebase