Muh*_*fan 5 php wordpress cart woocommerce shipping-method
我正在经营woocommerce商店,并使用统一费率送货$15。我写了一个公式$1.25为每个其他项目添加。
13.50 +(1.25 * [数量])
$1.25为附加的每个项目喝“统一费率设置| :
但是我想$1.25每3个项目加上这个费用。我的意思是3、6、9、12,依此类推...
谁能告诉我该怎么做?任何帮助表示赞赏。
更新 (2021)
\n以下代码将为每 3 件物品(3, 6, 9 \xe2\x80\xa6) 的统一费率运输方式添加额外费用。
\n您将需要使用简单的初始成本而不是公式来更改运费。
\n\n\n您可能需要在“运送选项”选项卡下的常规运送设置中“启用调试模式”,以暂时禁用运送缓存。
\n
代码(您将在其中设置额外运费):
\nadd_filter('woocommerce_package_rates', 'shipping_additional_cost_each_three_items', 10, 2);\nfunction shipping_additional_cost_each_three_items( $rates, $package ){\n if ( is_admin() && ! defined( 'DOING_AJAX' ) )\n return $rates;\n\n // HERE set your additional shipping cost\n $additional_cost = 1.25;\n $items_count = 0; // Initializing\n $each_items = 3; // Number of items (for additional cost)\n\n // Loop through cart items for the current shipping package \n foreach( $package['contents'] as $cart_item ) {\n $items_count = += $cart_item['quantity']; // Count cart items for current shipping package\n }\n\n if ( $items_count >= $each_items ) {\n // Loop through the shipping taxes array\n foreach ( $rates as $rate_key => $rate ){\n // Targetting "flat rate"\n if( 'flat_rate' === $rate->method_id ){\n $initial_cost = $new_cost = $rate->cost;\n $has_taxes = false; // Initializing\n $taxes = array(); // Initializing\n \n // Adding to cost the additional cost each 3 items (3, 6, 9 \xe2\x80\xa6)\n for($i = 0; $i <= $items_count; $i+ = $each_items){\n $new_cost += $additional_cost;\n }\n $rates[$rate_key]->cost = $new_cost; // Set the new cost\n \n // Taxes rate cost (if any) - Loop through taxes array (as they can be many)\n foreach ($rate->taxes as $key => $tax){\n if( $tax > 0 ){\n // Get the initial tax cost\n $initial_tax_cost = $new_tax_cost = $tax;\n // Get the tax rate conversion\n $tax_rate = $initial_tax_cost / $initial_cost;\n // Set the new tax cost\n $taxes[$key] = $new_cost * $tax_rate;\n $has_taxes = true; // Enabling tax changes\n }\n }\n // set array of shipping tax cost\n if( $has_taxes ) {\n $rates[$rate_key]->taxes = $taxes; \n }\n }\n }\n }\n return $rates;\n}\nRun Code Online (Sandbox Code Playgroud)\n代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并有效。
\n\n\n不要忘记在发货设置中禁用“启用调试模式”选项。
\n
根据您的第二条评论回答:
\n您将替换此块:
\n// Adding to cost the additional cost each 3 items (3, 6, 9 \xe2\x80\xa6)\nfor($i = 0; $i <= $items_count; $i += $each_items){\n $new_cost += $additional_cost;\n}\nRun Code Online (Sandbox Code Playgroud)\n通过以下方式:
\n// Adding to cost an additional fixed cost for the 2nd item\nif($items_count >= 2){\n $new_cost += 6.21; \n}\n\n// Adding to cost the additional cost each 3 items (3, 6, 9 \xe2\x80\xa6)\nfor($i = 0; $i <= $items_count; $i += $each_items){\n $new_cost += $additional_cost;\n}\nRun Code Online (Sandbox Code Playgroud)\n