防止在 WooCommerce 中访问没有送货方式的结帐

问题描述 投票:0回答:2

我正在尝试删除继续结帐按钮并限制对结帐页面的访问,直到客户在购物车页面上填写“计算运费”选项。

我创建了一种仅限于多个邮政/邮政编码的本地运输方式。然后我去把它添加到我的 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 );

然而,当我在不同的浏览器和隐身模式下测试网站时,“继续结帐”按钮就在那里。

如果我点击“计算运费”链接而不填写表格但更新它,按钮就会消失。我基本上希望当客户在能够继续结帐页面之前填写购物车页面上的“计算运费”表格(并且在我的送货方式中有一个邮政编码)时出现该按钮。

php wordpress woocommerce checkout shipping-method
2个回答
3
投票

您最好尝试使用 WooCommerce 会话中的“选择的运输方式”,例如:

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
动作挂钩:

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' );
    }
}

它应该更好用。


0
投票

上面的代码不起作用($chosen_shipping_methods 是一个数组,如果它有超过 0 个元素,则此条件将始终为真,因为 $chosen_shipping_methods 是一个在 WooCommerce 中使用默认值数组('')初始化的数组) ,所以我重新调整了它:

add_action( 'woocommerce_check_cart_items', 'required_chosen_shipping_methods' );
function required_chosen_shipping_methods() {
    $chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );

    // Check if $chosen_shipping_methods is an array and if it contains a valid shipping method
    if( is_array( $chosen_shipping_methods ) && ! in_array( '', $chosen_shipping_methods ) ) {
        // A valid shipping method has been selected, so do nothing
        return;
    }

    // Display an error message
    wc_add_notice( __("A shipping method is required in order to proceed to checkout."), 'error' );
}
© www.soinside.com 2019 - 2024. All rights reserved.