概要
woocommerce_shipping_zone_shipping_methods
フィルタは、WooCommerceで特定の配送ゾーンに関連する配送方法をカスタマイズするためのフックです。このフィルタを使用することで、開発者は特定の条件に基づいて配送方法を追加、削除、または変更することができます。一般的には、次のような機能を実装する際によく使われます。
- 配送方法のカスタマイズ
- 特定のユーザーグループ向けの配送方法を制御
- 地域または国に基づく配送オプションの調整
- プロモーションやディスカウントに応じた配送方法の追加
- 定期便サービスのための特別な配送メソッドの導入
- 送料が無料の条件を設定する際の配送メソッドの調整
構文
add_filter('woocommerce_shipping_zone_shipping_methods', 'カスタム関数名', 10, 2);
パラメータ
array $methods
: 既存の配送方法の配列WC_Shipping_Zone $zone
: 対象の配送ゾーンオブジェクト
戻り値
このフィルタは、修正された配送方法の配列を返します。
使用可能バージョン
- WooCommerce: バージョン2.6以降
- WordPress: バージョン4.0以降
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
1. 特定のユーザーグループに対して配送方法を無効にする
このサンプルでは、特定のユーザーグループに対して配送方法を削除します。
add_filter('woocommerce_shipping_zone_shipping_methods', 'remove_shipping_method_for_user_group', 10, 2);
function remove_shipping_method_for_user_group($methods, $zone) {
if (current_user_can('editor')) {
unset($methods['flat_rate']);
}
return $methods;
}
引用元: https://docs.woocommerce.com/document/introduction-to-hooks/
2. 特定の国向けにのみ配送方法を追加する
このコードは、特定の国に対してのみ新しい配送方法を追加します。
add_filter('woocommerce_shipping_zone_shipping_methods', 'add_shipping_method_for_country', 10, 2);
function add_shipping_method_for_country($methods, $zone) {
if (in_array('JP', $zone->get_region_ids())) {
$methods['custom_shipping_method'] = new WC_Shipping_Method();
}
return $methods;
}
引用元: https://woocommerce.com/document/woocommerce-shipping/
3. 配送方法の名称を変更する
このサンプルでは、特定の配送方法の名称を変更します。
add_filter('woocommerce_shipping_zone_shipping_methods', 'change_shipping_method_name', 10, 2);
function change_shipping_method_name($methods, $zone) {
if (isset($methods['flat_rate'])) {
$methods['flat_rate']->title = '特急配送';
}
return $methods;
}
引用元: https://developer.wordpress.org/reference/hooks/
4. 条件に応じて配送方法を切り替える
このサンプルでは、カート内の合計金額に応じて配送方法を切り替えます。
add_filter('woocommerce_shipping_zone_shipping_methods', 'conditional_shipping_methods', 10, 2);
function conditional_shipping_methods($methods, $zone) {
if (WC()->cart->total > 100) {
unset($methods['flat_rate']);
$methods['free_shipping'] = new WC_Shipping_Free_Shipping();
}
return $methods;
}
引用元: https://woocommerce.com/document/conditional-free-shipping/
5. 複数の新しい配送方法を追加する
このサンプルでは、複数の配送方法を追加します。
add_filter('woocommerce_shipping_zone_shipping_methods', 'add_multiple_shipping_methods', 10, 2);
function add_multiple_shipping_methods($methods, $zone) {
$methods['express_shipping'] = new WC_Shipping_Method();
$methods['overnight_shipping'] = new WC_Shipping_Method();
return $methods;
}
引用元: https://www.advancedcustomfields.com/resources/
これらのサンプルコードは、woocommerce_shipping_zone_shipping_methods
フィルタを使用して、様々な条件や要件に基づいた配送方法の管理を示しています。