Skip to content

Instantly share code, notes, and snippets.

@nczz
Last active December 26, 2019 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nczz/504b45194796e5ac2c609880ee2fc835 to your computer and use it in GitHub Desktop.
Save nczz/504b45194796e5ac2c609880ee2fc835 to your computer and use it in GitHub Desktop.
[WooCommerce] 運送方法項目的排序控制(指定順序)
<?php
function mxp_sort_shipping_methods_order($available_shipping_methods, $package) {
if (!$available_shipping_methods) {
return;
}
// 運送方式,檢視 radio 元素,找到的 value 值
$sort_order = array(
'flat_rate:1' => null,
'some_other_shipping_method_slug:3' => null,
'flat_rate:2' => null,
);
$others = array();
// 拆解
foreach ($available_shipping_methods as $shipping_slug => $shipping_obj) {
if (array_key_exists($shipping_slug, $sort_order)) {
$sort_order[$shipping_slug] = $available_shipping_methods[$shipping_slug];
} else {
$others[$shipping_slug] = $available_shipping_methods[$shipping_slug];
}
}
// 重組合併
$sort_order += $others;
foreach ($sort_order as $id => $null_obj) {
if (empty($null_obj)) {
// 去除不存在的選項
unset($sort_order[$id]);
}
}
return $sort_order;
}
add_filter('woocommerce_package_rates', 'mxp_sort_shipping_methods_order', 11, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment