概要
woocommerce_checkout_get_value
フィルタは、WooCommerceのチェックアウトプロセスにおいて、特定のフィールドのデフォルト値をカスタマイズするために使用されます。主に以下の機能に応じて使用されることが一般的です:
- 特定のカスタムフィールドの初期値の設定
- 顧客の過去の注文データから情報を引き出して自動入力
- 地域や国に基づいてデフォルトの配送先住所を変更
- プロモーションコードや割引情報を自動的に入力
- ユーザーのロールや権限に基づいて特定のフィールドのデフォルト値を変更
- その他フォームフィールドの値のダイナミックな変更
構文
add_filter('woocommerce_checkout_get_value', 'your_function', 10, 2);
パラメータ
$value
(mixed): チェックアウトフィールドのデフォルト値。$key
(string): フィールドのキー(例: ‘billing_first_name’)。
戻り値
フィルタリングされたデフォルト値。
使用可能バージョン
- WooCommerce: 3.0以降
- WordPress: 4.0以降
サンプルコード
サンプル1: 特定のカスタムフィールドの初期値の設定
このコードは「特別なプロモーション」のテキストを、カスタムフィールドの初期値として設定します。
add_filter('woocommerce_checkout_get_value', 'set_custom_promotion_value', 10, 2);
function set_custom_promotion_value($value, $key) {
if ($key === 'custom_promotion_field') {
return 'このプロモーションを使ってください!';
}
return $value;
}
引用元: https://docs.woocommerce.com/
サンプル2: 顧客の過去の注文データから情報を引き出して自動入力
このコードは、過去の注文から顧客の姓を引き出して、チェックアウトフォームに自動的に入力します。
add_filter('woocommerce_checkout_get_value', 'get_last_name_from_previous_orders', 10, 2);
function get_last_name_from_previous_orders($value, $key) {
if ($key === 'billing_last_name') {
$customer_orders = wc_get_orders(array('customer_id' => get_current_user_id()));
if (!empty($customer_orders)) {
return $customer_orders[0]->get_billing_last_name();
}
}
return $value;
}
引用元: https://developer.woocommerce.com/
サンプル3: 地域に基づいてデフォルトの配送先住所を変更
このコードは、顧客の国の地域に基づいてデフォルトの市町村を自動的に設定します。
add_filter('woocommerce_checkout_get_value', 'set_default_city_based_on_country', 10, 2);
function set_default_city_based_on_country($value, $key) {
if ($key === 'billing_city') {
$country = isset($_POST['billing_country']) ? $_POST['billing_country'] : '';
return $country === 'JP' ? '東京' : $value;
}
return $value;
}
引用元: https://www.wpbeginner.com/
サンプル4: 特定のロールに基づくデフォルト値の変更
このコードは特定のユーザーのロールに基づいてデフォルトの電話番号を設定します。
add_filter('woocommerce_checkout_get_value', 'set_default_phone_for_admin', 10, 2);
function set_default_phone_for_admin($value, $key) {
if ($key === 'billing_phone' && current_user_can('administrator')) {
return '1234567890';
}
return $value;
}
引用元: https://wptavern.com/
サンプル5: プロモーションコードの自動入力
このコードは、固定のプロモーションコードをチェックアウトフォームに自動的に追加します。
add_filter('woocommerce_checkout_get_value', 'auto_fill_coupon_code', 10, 2);
function auto_fill_coupon_code($value, $key) {
if ($key === 'coupon_code') {
return 'SAVE20';
}
return $value;
}
引用元: https://wordpress.stackexchange.com/
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |