概要
woocommerce_shipping_methods
フィルタは、WooCommerceにおける配送方法のカスタマイズを行う際に使用されます。このフィルタは、WooCommerceの配送オプションをフックし、新しい配送方法を追加したり、既存の配送方法を修正したりするために特に役立ちます。以下のような場合に活用されることが一般的です。
- 独自配送方法の追加
- 配送コストの計算のカスタマイズ
- 特定の地域の配送制限の設定
- プロモーション用の特別割引配送方法の設定
- 複数の配送サービスからの選択肢の統合
- ユーザーによる配送方法の選択の最適化
構文
add_filter( 'woocommerce_shipping_methods', 'custom_shipping_methods' );
function custom_shipping_methods( $methods ) {
// カスタム配送方法を追加
return $methods;
}
パラメータ
$methods
: 既存の配送方法の配列
戻り値
- 配送方法の配列。新しい配送方法が追加された状態で返される。
互換性
- WooCommerce バージョン: すべてのバージョン
- WordPress バージョン: すべてのバージョン
サンプルコード
サンプルコード1: 独自配送方法の追加
add_filter( 'woocommerce_shipping_methods', 'add_custom_shipping_method' );
function add_custom_shipping_method( $methods ) {
$methods['custom_shipping'] = 'WC_Custom_Shipping_Method'; // カスタム配送クラス名を追加
return $methods;
}
このコードは、カスタム配送方法 “custom_shipping” をWooCommerceの配送方法に追加します。クラス名は事前に定義する必要があります。
サンプルコード2: 配送コストの動的計算
add_filter( 'woocommerce_shipping_methods', 'dynamic_shipping_cost' );
function dynamic_shipping_cost( $methods ) {
// 配送コストの計算ロジックを実装
return $methods;
}
このサンプルは配送コストを動的に計算するための骨組みを提供します。
サンプルコード3: 特定地域専用の配送方法の設定
add_filter( 'woocommerce_shipping_methods', 'region_specific_shipping' );
function region_specific_shipping( $methods ) {
if ( is_user_logged_in() ) {
// ログインユーザー専用の配送方法を追加
}
return $methods;
}
このコードは、特定の条件に基づいて配送方法を設定する際の基盤となります。
サンプルコード4: 配送方法のラベルの変更
add_filter( 'woocommerce_shipping_methods', 'change_shipping_method_label' );
function change_shipping_method_label( $methods ) {
if ( isset( $methods['flat_rate'] ) ) {
$methods['flat_rate']->title = '標準送料'; // ラベルを変更
}
return $methods;
}
このサンプルでは、配送方法のラベルを変更する方法を示しています。
サンプルコード5: 配送方法の削除
add_filter( 'woocommerce_shipping_methods', 'remove_shipping_method' );
function remove_shipping_method( $methods ) {
unset( $methods['free_shipping'] ); // 無料配送を削除
return $methods;
}
このコードは、特定の配送方法(ここでは無料配送)をリストから削除します。
この関数のアクションでの使用可能性
アクション | 使用可能 |
---|---|
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 |