我正在尝试删除继续结帐按钮并限制对结帐页面的访问,直到客户在购物车页面上填写“计算运费”选项。
我创建了一个仅限于多个邮政编码的本地送货方式。然后我将其添加到我的 functions.php 文件中。
function disable_checkout_button_no_shipping() {
$package_counts = array();
// get shipping packages and their rate counts
$packages = WC()->shipping->get_packages();
foreach( $packages as $key => $pkg )
$package_counts[ $key ] = count( $pkg[ 'rates' ] );
// remove button if any packages are missing shipping options
if( in_array( 0, $package_counts ) )
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
}
add_action( 'woocommerce_proceed_to_checkout', 'disable_checkout_button_no_shipping', 1 );
但是,当我在不同的浏览器和隐身模式下测试网站时,“继续结帐”按钮就在那里。
如果我点击“计算运费”链接而不是填写表格但更新它,按钮就会消失。我基本上希望当客户在能够继续到结帐页面之前填写购物车页面上的“计算运费”表格(并且在我的送货方式中有一个邮政编码)时出现该按钮。
最佳答案
您最好尝试使用 WooCommerce session 中的“选择的送货方式”,例如:
function disable_checkout_button_no_shipping() {
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
// remove button if there is no chosen shipping method
if( empty( $chosen_shipping_methods ) ) {
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
}
}
add_action( 'woocommerce_proceed_to_checkout', 'disable_checkout_button_no_shipping', 1 );
或者以不同的方式使用 woocommerce_check_cart_items
操作 Hook :
add_action( 'woocommerce_check_cart_items', 'required_chosen_shipping_methods' );
function required_chosen_shipping_methods() {
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );
if( is_array( $chosen_shipping_methods ) && count( $chosen_shipping_methods ) > 0 ) {
// Display an error message
wc_add_notice( __("A shipping method is required in order to proceed to checkout."), 'error' );
}
}
它应该能更好地工作。
关于php - 防止在 WooCommerce 中访问没有运输方式的结帐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61065801/