概要
woocommerce_shipping_rate_instance_id
フィルタは、WooCommerceでの送料計算の際に使用される重要なフックです。このフィルタは、配送方法のインスタンスIDを変更またはカスタマイズするために使用され、発送オプションごとの特定の識別子を提供します。このフィルタは、商品の特性やカスタム配送設定に基づいて、様々な条件付きの料金設定を行う際に非常に便利です。
このフィルタを使用してよく実装される機能には、以下のようなものがあります:
1. カスタム配送メソッドの追加
2. ユーザーのロールに基づく送料の調整
3. 購入数量に基づく送料の変更
4. 地域に基づく送料のカスタマイズ
5. スペシャルプロモーションや割引を反映させた送料設定
6. 複数の配送オプションの条件付き表示
構文
apply_filters( 'woocommerce_shipping_rate_instance_id', $instance_id, $method, $rate );
パラメータ
- $instance_id (string): 配送方法のインスタンスID。
- $method (WC_Shipping_Method): 現在の配送メソッドオブジェクト。
- $rate (array): 配送料金の詳細を含む連想配列。
戻り値
- (string): フィルタ後の配送メソッドのインスタンスID。
対応するWooCommerceとWordPressのバージョン
- WooCommerce: すべてのバージョンで使用可能
- WordPress: すべてのバージョンで使用可能
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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: インスタンスIDのカスタマイズ
add_filter( 'woocommerce_shipping_rate_instance_id', 'custom_shipping_instance_id', 10, 3 );
function custom_shipping_instance_id( $instance_id, $method, $rate ) {
if ( $method->id === 'flat_rate' ) {
$instance_id = 'flat_rate_custom_' . uniqid();
}
return $instance_id;
}
このコードは、フラットレート配送メソッドのインスタンスIDをカスタムIDに変更しています。
サンプル2: 配送方法による条件付きロジック
add_filter( 'woocommerce_shipping_rate_instance_id', 'conditional_shipping_instance_id', 10, 3 );
function conditional_shipping_instance_id( $instance_id, $method, $rate ) {
if ( is_user_logged_in() && $method->id === 'free_shipping' ) {
$instance_id .= '_logged_in';
}
return $instance_id;
}
このコードは、ユーザーがログインしている場合に無料配送のインスタンスIDにサフィックスを追加します。
サンプル3: 複数の配送条件に基づくインスタンスIDの変更
add_filter( 'woocommerce_shipping_rate_instance_id', 'multiple_conditions_shipping_instance_id', 10, 3 );
function multiple_conditions_shipping_instance_id( $instance_id, $method, $rate ) {
if ( WC()->cart->total > 100 ) {
$instance_id .= '_bulk_order';
}
return $instance_id;
}
このコードは、カートの合計が100を超える場合に特定のインスタンスIDを追加します。
サンプル4: デフォルトインスタンスIDの変更
add_filter( 'woocommerce_shipping_rate_instance_id', 'default_instance_id_change', 10, 3 );
function default_instance_id_change( $instance_id, $method, $rate ) {
if ( $method->id === 'local_pickup' ) {
return 'pickup_location_' . $instance_id;
}
return $instance_id;
}
このコードは、ローカルピックアップオプションのインスタンスIDにカスタム文字列を追加します。
サンプル5: 特定の配送方法のためのユニークなID
add_filter( 'woocommerce_shipping_rate_instance_id', 'unique_shipping_id_per_method', 10, 3 );
function unique_shipping_id_per_method( $instance_id, $method, $rate ) {
if ( 'flat_rate_1' === $method->id ) {
$instance_id = 'better_flat_rate_' . $rate['id'];
}
return $instance_id;
}
このコードは、特定のフラットレート配送メソッドに基づいてインスタンスIDをユニークに生成します。