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

概要

woocommerce_order_shipping_method フィルタは、WooCommerceの注文に関連する配送方法をカスタマイズするために使用されるフックです。このフィルタを使用することで、デフォルトの配送方法や送料を変更したり、オプションを追加したりすることができます。主に次のような機能を実装する際に利用されます。

  1. 複数の配送オプションを提供する
  2. 特定の条件に基づいて送料を変更する
  3. カスタム配送メソッドを追加する
  4. 配送方法の説明を変更する
  5. 複雑な料金計算を実装する
  6. タグやクラスを使用して配送方法をスタイリングする

構文

add_filter('woocommerce_order_shipping_method', 'custom_shipping_method', 10, 2);

パラメータ

  • $method (string): デフォルトの配送方法。
  • $order (WC_Order): 現在の注文オブジェクト。

戻り値

  • (string): フィルタ処理後の配送方法。

使用可能なプラグインバージョン

  • 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_order_shipping_method', 'change_shipping_method_based_on_condition', 10, 2);
function change_shipping_method_based_on_condition($method, $order) {
    if ($order->get_total() > 100) {
        return 'free_shipping';
    }
    return $method;
}

引用元: https://docs.woocommerce.com/document/what-are-hooks/

サンプル2: カスタム配送メソッドの追加

このサンプルでは、カスタム配送メソッドを追加します。

add_filter('woocommerce_order_shipping_method', 'add_custom_shipping_method', 10, 2);
function add_custom_shipping_method($method, $order) {
    return 'my_custom_shipping_method';
}

引用元: https://woocommerce.com/document/custom-delivery-methods/

サンプル3: 配送方法の説明を変更

このサンプルでは、配送方法の説明を変更します。

add_filter('woocommerce_order_shipping_method', 'modify_shipping_method_description', 10, 2);
function modify_shipping_method_description($method, $order) {
    if ($method === 'flat_rate') {
        return 'Flat Rate - Fast and reliable shipping.';
    }
    return $method;
}

引用元: https://woocommerce.com/document/change-shipping-methods/

サンプル4: プロモーションに基づく送料の変更

このサンプルは、プロモーションに基づいて送料を変更します。

add_filter('woocommerce_order_shipping_method', 'promo_based_shipping', 10, 2);
function promo_based_shipping($method, $order) {
    if ($order->get_discount_total() > 0) {
        return 'discounted_shipping_method';
    }
    return $method;
}

引用元: https://woocommerce.com/document/advanced-shipping-rules/

サンプル5: 特殊条件の配送方法の表示

このサンプルは、特定の場所や条件に依存した配送方法を表示します。

add_filter('woocommerce_order_shipping_method', 'conditional_shipping_method', 10, 2);
function conditional_shipping_method($method, $order) {
    $shipping_destination = $order->get_shipping_country();
    if ($shipping_destination === 'JP') {
        return 'japan_only_shipping_method';
    }
    return $method;
}

引用元: https://woocommerce.com/document/add-your-own-shipping-methods/

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


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