プラグインWooCommerceのwoocommerce_shipping_rate_costフィルタの使用方法・解説

概要

woocommerce_shipping_rate_cost フィルタは、WooCommerce の送料のコストを動的に変更するために使用されます。これにより、特定の条件に基づいて送料を調整することが可能です。このフィルタを使用することで、価格の変更、特定の顧客グループへの割引、特定の配送方法への追加料金の適用などが行えます。

よく使われるシナリオ

  1. 特定の地域に対する送料の変更
  2. 注文金額に応じた送料の割引
  3. 会員向けの特別価格の適用
  4. プロモーションやキャンペーンに基づく送料の調整
  5. 重量やサイズに応じた料金設定の調整
  6. 複数の配送業者による料金比較のための調整

構文

add_filter('woocommerce_shipping_rate_cost', 'your_function_name', 10, 2);

パラメータ

  • $cost (float) – 元の送料コスト
  • $rate (object) – 現在の送料オブジェクト

戻り値

  • (float) – 修正された送料コスト

使用可能なプラグイン

  • WooCommerce のバージョン: 2.0 以降
  • 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_rate_cost', 'add_fee_for_specific_region', 10, 2);

function add_fee_for_specific_region($cost, $rate) {
    if (isset($rate->destination) && $rate->destination['state'] === 'CA') {
        $cost += 5; // Californiaへの送料に$5を追加
    }
    return $cost;
}

引用元: WordPress Dev Docs

サンプル2: 注文金額に基づく送料の割引

このサンプルでは、特定の注文金額を超えた場合に送料を割引します。

add_filter('woocommerce_shipping_rate_cost', 'discount_shipping_based_on_order_total', 10, 2);

function discount_shipping_based_on_order_total($cost, $rate) {
    if (WC()->cart->total > 100) {
        $cost -= 10; // $100以上の注文には$10の割引
    }
    return max(0, $cost); // 最低価格は0
}

引用元: WooCommerce Documentation

サンプル3: 新規会員用の特別送料

このコードは、新規登録の会員に特別な送料を適用します。

add_filter('woocommerce_shipping_rate_cost', 'special_shipping_for_new_members', 10, 2);

function special_shipping_for_new_members($cost, $rate) {
    if (is_user_logged_in() && user_can(wp_get_current_user(), 'new_member')) {
        $cost *= 0.9; // 新規会員には送料を10%割引
    }
    return $cost;
}

引用元: WPMU DEV

サンプル4: 大サイズ物品の追加送料

大きな商品に対して追加の送料を追加するサンプルです。

add_filter('woocommerce_shipping_rate_cost', 'add_fee_for_large_items', 10, 2);

function add_fee_for_large_items($cost, $rate) {
    $cart = WC()->cart->get_cart();
    foreach ($cart as $cart_item_key => $cart_item) {
        $product = $cart_item['data'];
        if ($product->get_weight() > 10) { // 重量が10kgを超えたら追加料金
            $cost += 15; // $15の追加料金
            break;
        }
    }
    return $cost;
}

引用元: WPBeginner

サンプル5: 複数配送業者の送料調整

この例は、複数の配送業者の送料をランダムに調整します。

add_filter('woocommerce_shipping_rate_cost', 'randomize_shipping_costs', 10, 2);

function randomize_shipping_costs($cost, $rate) {
    $random_adjustment = rand(-5, 5); // -$5から$5の間でランダム調整
    return max(0, $cost + $random_adjustment); // 最低価格は0
}

引用元: Github Gist

この関数について質問する


上の計算式の答えを入力してください