概要
woocommerce_before_save_order_items
は、WooCommerceのプラグインで使用されるフックの一つで、新しい注文アイテムが保存される前に実行されます。これにより、注文アイテムデータを加工したり、追加の操作を実行したりすることができます。このアクションは、以下のような場合に役立ちます:
- カスタムメタデータの追加
- 注文アイテムの検証
- 割引計算の適用
- 在庫の確認および調整
- 通知のトリガー
- 外部APIとの連携
構文
do_action('woocommerce_before_save_order_items', $order_id, $item_id, $item_data);
パラメータ
$order_id
(int): 注文のID。$item_id
(int): 注文アイテムのID。$item_data
(array): 注文アイテムに関するデータの配列。
戻り値
このアクションは値を返しませんが、フックを使用する関数内でプロセスを変更や加工することができます。
使用可能なプラグインバージョン
- WooCommerce: 3.0+
- WordPress: 4.0+
サンプルコード
サンプル1: 注文アイテムにカスタムメタデータを追加
このコードは、注文アイテムが保存される際にカスタムメタデータを追加します。
add_action('woocommerce_before_save_order_items', 'add_custom_order_item_meta', 10, 3);
function add_custom_order_item_meta($order_id, $item_id, $item_data) {
$custom_value = 'カスタム値';
wc_add_order_item_meta($item_id, 'custom_meta', $custom_value);
}
引用元: https://example.com
サンプル2: 注文アイテムの価格を調整
このコードは、注文アイテムの価格を条件に基づいて変更します。
add_action('woocommerce_before_save_order_items', 'adjust_order_item_price', 10, 3);
function adjust_order_item_price($order_id, $item_id, $item_data) {
$item = wc_get_order_item($item_id);
if ($item->get_product_id() === 123) { // 特定の商品ID
$item->set_total($item->get_total() * 0.9); // 10%引き
}
}
引用元: https://example.com
サンプル3: 注文アイテムの在庫を調整
このコードは、アイテムが保存される前に在庫を調整します。
add_action('woocommerce_before_save_order_items', 'adjust_stock_before_order_item_save', 10, 3);
function adjust_stock_before_order_item_save($order_id, $item_id, $item_data) {
$item = wc_get_order_item($item_id);
$product = wc_get_product($item->get_product_id());
if ($product) {
$product->decrease_stock_quantity($item->get_quantity());
}
}
引用元: https://example.com
サンプル4: 特定の条件でのカスタム通知の送信
このコードは、特定の条件に基づいてカスタム通知を送信します。
add_action('woocommerce_before_save_order_items', 'send_custom_notification', 10, 3);
function send_custom_notification($order_id, $item_id, $item_data) {
if ($item_data['product_id'] == 456) { // 特定のプロダクトID
wp_mail('example@example.com', '通知', '特定の商品が注文されました。');
}
}
引用元: https://example.com
サンプル5: 割引適用の確認
このコードは、割引が適用されるかどうかを確認するためにコードを実行します。
add_action('woocommerce_before_save_order_items', 'check_for_discount', 10, 3);
function check_for_discount($order_id, $item_id, $item_data) {
$item = wc_get_order_item($item_id);
if ($item->get_total() > 100) { // 価格が100を超える場合
// 割引条件の処理
}
}
引用元: https://example.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 |