首页 > 解决方案 > 如何在 woocomerce、wordpress 中隐藏条件函数的运输方式?

问题描述

我不知道如何在 functions.php 文件中创建和定义全局变量。我在 Wordpress 中使用 WooCommerce (3.7.1)。

我创建了一个名为action_before_cart()的函数,如果购物车包含 X 产品,该函数会检查许多条件。在此函数中,我声明了一个名为$shipping的全局变量,使用此函数后的值应为:0 或 1。

现在,根据 $shipping 全局变量的值,在 hide_shipping_method_based_on_shipping_method 函数中,在购物车或结帐时,只会隐藏一些选定的运输方式。我通过 unset($rates[$method_key_id]); 取消设置每个方法来做到这一点 在每个循环中。

所以基本上我想做的是在函数 action_before_cart() 中获取全局变量 $shipping 并在 hide_shipping_method_based_on_shipping_method 函数中使用它。

add_action('woocommerce_before_cart', 'action_before_cart');
        function action_before_cart() {

            $hasOfficePack = false;
            $hasSundayCombo = false;

            $officePack = array('office pack', '77');
            $sundayCombo = array('sunday combo', '85');

            // Loop through cart items if there's $officePack or $sundayCombo
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                // Check for $officePack category products in cart
                if ( has_term( $officePack, 'product_cat', $cart_item['product_id'] ) ) {
                    $hasOfficePack = true;
                }
                // Check for $sundayCombo category products in cart
                if ( has_term( $sundayCombo, 'product_cat', $cart_item['product_id'] ) ) {
                    $hasSundayCombo  = true;
                }
            }

            global $shipping; //the most important variable, which I want to be saved and used in the next function below

            if ( $hasOfficePack ) { 
                $shipping = 0;
            }

            if ( $hasSundayCombo ) { 
                $shipping = 1;
            }


        }

add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_method', 1, 2 );
        function hide_shipping_method_based_on_shipping_method( $rates, $package ) {

            global $shipping; //the value of $shipping it's supposed to be set in the previous function

            if ( is_admin() && ! defined( 'DOING_AJAX' ) )
                return;

            if ($shipping == 0) {
                $method_key_ids = array('flat_rate:2', 'free_shipping:8', 'flat_rate:9');
            } elseif($shipping == 1) {
                $method_key_ids = array('flat_rate:2', 'flat_rate:9');
            }

            foreach( $method_key_ids as $method_key_id ){
                unset($rates[$method_key_id]); // Remove the targeted methods
            }

            return $rates;

        }

标签: phpwordpresswoocommercecheckouthook-woocommerce

解决方案


推荐阅读