首页 > 解决方案 > 计算 1 件产品而不是整个购物车的运费

问题描述

我已经在单个产品的页面中安装了一个用于计算运费的插件。该插件将产品添加到购物车中,计算运费(整个购物车 + 该产品),然后将其删除。

我想计算该产品的运费(应该是复制当前购物车,清空购物车,将此产品添加到购物车计算运费,清理购物车从副本中回滚购物车?)任何人都有如何修改的建议上面的代码以便仅计算当前产品?

/* function for calculate shiiping */

    public function get_shipping_text($shipping_method, $country)
    {
        global $woocommerce, $post;
        $returnResponse = array();
        WC_Shortcode_Cart::calculate_shipping();


        if (isset($_POST["product_id"]) && $this->check_product_incart($_POST["product_id"]) === false) {
            $qty = (isset($_POST['current_qty']) && $_POST['current_qty'] > 0) ? $_POST['current_qty'] : 1;
            if (isset($_POST['variation_id']) && $_POST['variation_id'] != "" && $_POST['variation_id'] > 0) {
                $cart_item_key = WC()->cart->add_to_cart(sanitize_text_field($_POST["product_id"]), $qty, sanitize_text_field($_POST['variation_id']));
            } else {
                $cart_item_key = WC()->cart->add_to_cart(sanitize_text_field($_POST["product_id"]), $qty);
            }
            $packages = WC()->cart->get_shipping_packages();
            $packages = WC()->shipping->calculate_shipping($packages);
            $packages = WC()->shipping->get_packages();
            WC()->cart->remove_cart_item($cart_item_key);
        } else {
            $packages = WC()->cart->get_shipping_packages();
            $packages = WC()->shipping->calculate_shipping($packages);
            $packages = WC()->shipping->get_packages();
        }

        wc_clear_notices();

        if (isset($packages[0]["rates"][$shipping_method])) {
            $selectedShiiping = $packages[0]["rates"][$shipping_method];
            $returnResponse = array("label" => $selectedShiiping->label, "cost" => wc_price(($selectedShiiping->cost)*1.24));
        } else {
            $AllMethod = WC()->shipping->load_shipping_methods();
            $selectedMethod = $AllMethod[$shipping_method];
            $flag = 0;
            if ($selectedMethod->availability == "including"):
                foreach ($selectedMethod->countries as $methodcountry) {
                    if ($country == $methodcountry) {
                        $flag = 1;
                    }
                }
                if ($flag == 0):
                    $message = $selectedMethod->method_title . " is not available in selected country.";
                    $returnResponse = array("code" => "error", "message" => $message);
                endif;
            endif;
        }
        return $returnResponse;
    }

标签: phpwordpresswoocommerce

解决方案


推荐阅读