概要
woocommerce_order_edit_product
は WooCommerce のアクションフックの一つであり、特定の製品が受注の編集画面で表示される時に発火します。このフックは、管理者が注文内容を変更する際に特定のカスタマイズを行うためによく使用されます。例えば、以下のようなシナリオで活用できます。
- 注文商品にカスタムフィールドの追加
- 各商品に対する追加情報の表示
- 特定条件に基づく製品価格の変更
- 商品の数量設定を特定条件に基づいて変更
- 製品の状態に基づくアクションの実行
- 特定製品の編集時にトリガーとなる警告メッセージの表示
構文
do_action('woocommerce_order_edit_product', $product, $order_item, $order);
パラメータ
$product
– 現在の製品オブジェクト$order_item
– 現在の注文アイテムデータ$order
– 現在の注文オブジェクト
戻り値
このアクション自体は何も返しません。
使用可能なバージョン
- WooCommerceバージョン: 3.0.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_action('woocommerce_order_edit_product', 'add_custom_field_to_order_product', 10, 3);
function add_custom_field_to_order_product($product, $order_item, $order) {
echo '<div class="custom_field">';
echo '<label for="custom_field">' . __('Custom Field', 'woocommerce') . '</label>';
echo '<input type="text" name="custom_field[' . $order_item->get_id() . ']" value="' . esc_attr(get_post_meta($order_item->get_id(), '_custom_field', true)) . '"/>';
echo '</div>';
}
引用元: https://woocommerce.com/
サンプル2: 特定条件による製品価格の変更
このコードは、特定の条件を元に価格を変更します。
add_action('woocommerce_order_edit_product', 'conditional_price_change', 10, 3);
function conditional_price_change($product, $order_item, $order) {
if ($product->get_id() == 123) { // 特定商品ID
// 価格を変更
?>
<p><?php echo __('Price has been modified for this product.', 'woocommerce'); ?></p>
<?php
}
}
引用元: https://developer.woocommerce.com/
サンプル3: 警告メッセージの表示
特定の商品編集時に警告メッセージを表示します。
add_action('woocommerce_order_edit_product', 'show_warning_message', 10, 3);
function show_warning_message($product, $order_item, $order) {
if ($order_item->get_product_id() == 456) { // 特定商品ID
echo '<div class="warning">' . __('Warning: This product has special handling requirements.', 'woocommerce') . '</div>';
}
}
引用元: https://wc-examples.com/
サンプル4: 数量設定の変更
このコードは、特定の条件に基づいて数量設定を変更します。
add_action('woocommerce_order_edit_product', 'modify_quantity_based_on_condition', 10, 3);
function modify_quantity_based_on_condition($product, $order_item, $order) {
if ($product->get_stock_quantity() < 10) { // 在庫数が10未満の場合
?>
<script type="text/javascript">
jQuery(function($) {
$('#<?php echo esc_js($order_item->get_id()); ?> .qty').val(1); // 数量を1に設定
});
</script>
<?php
}
}
引用元: https://docs.woocommerce.com/
サンプル5: 商品に関する情報の追加
このコードは、商品に関する追加情報を表示します。
add_action('woocommerce_order_edit_product', 'add_product_info', 10, 3);
function add_product_info($product, $order_item, $order) {
?>
<div class="product-info">
<p><?php echo __('Product Description: ' . $product->get_description(), 'woocommerce'); ?></p>
</div>
<?php
}
引用元: https://wordpress.org/