javascript - 每次 WooCommerce 购物车为空时,如何让脚本运行?
问题描述
在 WooCommerce 中,在空的购物车挂钩上运行以下函数。因此,从技术上讲,每次 woocommerce 购物车为空时都会运行。如果我在购物车为空时去 directlinkdotcom/cart/,则脚本运行良好。但是,如果我从购物车中删除物品以使其在放入物品后将其清空,则脚本不会按预期执行。我究竟做错了什么?
function mdoulos_show_custom_empty_cart() {
?>
<script type="text/javascript" defer>
let cartTitle = document.querySelector('.entry-title');
let progressBar = document.querySelector('.pbar-cart');
let customHeading = document.querySelector('.empty-heading');
let customDescription = document.querySelector('.empty-description');
let customTruck = document.querySelector('.empty-truck');
let cartCategories = customTruck.nextElementSibling;
let standardNotice = customTruck.nextElementSibling.nextElementSibling;
cartTitle.style.display = "none";
progressBar.style.display = "none";
standardNotice.style.display = "none";
customHeading.style.display = "block";
customDescription.style.display = "block";
customTruck.style.display = "block";
cartCategories.style.display = "block";
</script>
<?php
}
remove_action( 'woocommerce_cart_is_empty', 'wc_empty_cart_message', 10 );
add_action( 'woocommerce_cart_is_empty', 'mdoulos_show_custom_empty_cart', 10 );
解决方案
我认为您可能会错过删除项目时在幕后发生的 AJAX 功能。在页面加载时运行代码与在删除某些产品并最终得到一个空购物车后运行的代码之间存在差异。这解释了您在页面刷新时注意到的内容。
除了您已经在使用的代码之外,您可能还需要这样的东西:
function my_cart_updated( $item_id ) {
// check if cart contents are empty
if ( WC()->cart->get_cart_contents_count() == 0 ) {
// do whatever you want here
// ...
}
}
// add the action
add_action( 'woocommerce_cart_item_removed', 'my_cart_updated' );
我认为这样的事情可能会奏效:
function my_cart_updated( $item_id ) {
// check if cart contents are empty
if ( WC()->cart->get_cart_contents_count() == 0 ) {
?>
<script type="text/javascript" defer>
let cartTitle = document.querySelector('.entry-title');
let progressBar = document.querySelector('.pbar-cart');
let customHeading = document.querySelector('.empty-heading');
let customDescription = document.querySelector('.empty-description');
let customTruck = document.querySelector('.empty-truck');
let cartCategories = customTruck.nextElementSibling;
let standardNotice = customTruck.nextElementSibling.nextElementSibling;
cartTitle.style.display = "none";
progressBar.style.display = "none";
standardNotice.style.display = "none";
customHeading.style.display = "block";
customDescription.style.display = "block";
customTruck.style.display = "block";
cartCategories.style.display = "block";
</script>
<?php
}
}
// add the action
add_action( 'woocommerce_cart_item_removed', 'my_cart_updated' );
推荐阅读
- chef-infra - 无法在厨房使用厨师导出 data_bag 项目
- intellij-idea - 知道如何知道一个罐子来自哪里
- java - 如何在我的 java 计算器程序中获得用户输入验证?
- java - 如何覆盖 System.out.println(map)
- adb - 使用“发送到”窗口快捷方式进行 ADB 推送的批处理文件
- google-cloud-run - Cloud Run 构建 API 最佳实践
- sql - PostgreSQL查询具有字符串值而不是JSON对象的JSONB列
- amazon-web-services - AWS 中的实时通知(无服务器)
- java - 在 Java 中为用户输入垂直对齐文本框时遇到问题
- flutter - Flutter Firestore _MapStream
不是 Stream 的子类型