php - WooCommerce:按国家/地区代码获取运输方式
问题描述
我正在尝试通过在请求中提供的国家/地区代码获取可用的运输方法,在上面的代码中我面临问题/冲突
可用的位置可以是 acountry
或 acontinent
所以我需要检查这个国家代码是否是某个大陆的一部分。
问题在于第一个区域我得到了所有区域中的所有方法,而不仅仅是第一个区域(回调返回)。
第二个区域有大陆/国家(世界其他地区),我对此没有任何问题,但据我所知,这是因为它是循环的尽头。(因为我现在有两个区域)
add_action("rest_api_init", function () {
register_rest_route(
"test-api/v1",
"shipping-cost",
array(
'callback' => function ($req) {
$country_code = $req->get_param('country_code');
$quantity = $req->get_param('quantity');
$shipping_cost = 0;
$methodes = [];
if (class_exists('WC_Shipping_Zones')) {
$all_zones = WC_Shipping_Zones::get_zones();
if (!empty($all_zones)) {
foreach ($all_zones as $zone) {
if (!empty($zone['zone_locations'])) {
foreach ($zone['zone_locations'] as $location) {
$wc_contries = new WC_Countries();
$continent_code = $wc_contries->get_continent_code_for_country($country_code);
if ($country_code === $location->code || $continent_code === $location->code) {
if (!empty($zone['shipping_methods'])) {
$shipping_method_ctrl = new WC_REST_Shipping_Zone_Methods_Controller();
foreach ($zone['shipping_methods'] as $flat_rate) {
$shipping_method = $shipping_method_ctrl->prepare_item_for_response($flat_rate, $req);
$methodes[] = (object) $shipping_method;
}
}
}
}
}
}
}
}
return $methodes;
}
)
);
});
解决方案
这是答案:(加上break
数组的数量希望它停止)
Register_rest_route(
"kefan-api/v1",
"shipping-cost",
array(
'callback' => function ($req) {
$country_code = $req->get_param('country_code');
$methodes = [];
if (class_exists('WC_Shipping_Zones')) {
$all_zones = WC_Shipping_Zones::get_zones();
if (!empty($all_zones)) {
foreach ($all_zones as $zone) {
if (!empty($zone['zone_locations'])) {
foreach ($zone['zone_locations'] as $location) {
$wc_contries = new WC_Countries();
$continent_code = $wc_contries->get_continent_code_for_country($country_code);
if ($country_code === $location->code || $continent_code === $location->code) {
if (!empty($zone['shipping_methods'])) {
$shipping_method_ctrl = new WC_REST_Shipping_Zone_Methods_Controller();
foreach ($zone['shipping_methods'] as $flat_rate) {
$shipping_method = $shipping_method_ctrl->prepare_item_for_response($flat_rate, $req);
$methodes[] = (object) $shipping_method;
}
break 2;
}
}
}
}
}
}
}
return $methodes;
}
)
);
推荐阅读
- c++ - g++ 和 clang++ 对类/方法可变参数模板类型的不同行为
- ruby-on-rails - Rails 成员路径前缀在更改路由后未更新
- java - 抽象父类调用派生类方法
- android - 如何在移动和nodejs一起使用的应用程序中使用linkedin登录
- axon - 多实体聚合命令处理
- regex - 如何查找以“/”开头并包含“php”的 URL?
- javascript - 不可见的字符导致意外的 EOF 错误
- scala - Spark Scala - 批量并行处理不同的子数据帧
- android - Android mkdir() 无法在可移动微型 SD 卡的根目录中创建文件夹
- python - 如何从列表中选择一个值窗口?