php - 在 woocommerce_before_calculate_totals 挂钩中获取购物车小计
问题描述
我想在woocommerce_before_calculate_totals
钩子内的 woocommerce 中获取购物车内容的总数。所以为了实现这一点,我正在使用这段代码
add_action( 'woocommerce_before_calculate_totals', 'get_before_calculate_totals', 10 );
function get_before_calculate_totals( $cart_object ) {
global $woocommerce;
echo WC()->cart->get_cart_contents_total(); //returns 0
}
但它每次都返回 0。那么有人可以告诉我如何在没有货币的情况下获得购物车总数woocommerce_before_calculate_totals
吗?
任何帮助和建议都将是非常可观的。
解决方案
正如woocommerce_before_calculate_totals
在任何总计计算之前使用的那样,请使用以下内容来进行项目小计计算:
add_action( 'woocommerce_before_calculate_totals', 'get_subtotal_before_calculate_totals', 10 );
function get_subtotal_before_calculate_totals( $cart ) {
$subtotal_excl_tax = $subtotal_incl_tax = 0; // Initializing
// Loop though cart items
foreach( $cart->get_cart() as $cart_item ) {
$subtotal_excl_tax += $cart_item['line_subtotal'];
$subtotal_incl_tax += $cart_item['line_subtotal'] + $cart_item['line_subtotal_tax'];
}
echo '<p>Subtotal excl. tax: ' . $subtotal_excl_tax . '</p>'; // Testing output
echo '<p>Subtotal Incl. tax: ' . $subtotal_incl_tax . '</p>'; // Testing output
}
推荐阅读
- postgresql - 如何核对 postgres 模式?
- python - 检查数据框单元格是否包含另一个数据框单元格中的值
- linux - 在分叉之前或之后在磁盘文件上调用 mmap() 有什么区别?
- java - 无法使用 Sendgrid SMPT 触发高优先级电子邮件到 Java 中的 Outlook
- python - 如何从文件中的 3D 列表/数组中提取数据以进行计算
- ajax - Morris.js x Axis 排列不正确
- laravel - 当我尝试 detach() 时返回错误:local.ERROR: Call to a member function programs() on integer
- azure-devops - 给定一个组,我如何检索组的 Microsoft.TeamFoundation.Identity(设置安全权限)
- c++ - 委托构造函数的评估
- javascript - 克隆行时自动删除下拉列表中的选定选项