概要
woocommerce_update_product
アクションフックは、WooCommerce プラグインで商品の情報が更新されたときに呼び出されます。このフックは、商品の更新時に特定の処理を実行したい場合に非常に便利です。例えば、商品情報の変更が行われた際に他のデータベースを更新したり、外部APIに通知を送信したりする場合に使用されます。一般的に、以下のような機能を実装する際によく使われます。
- 商品情報の変更ログ記録
- 在庫管理システムとの連携
- 外部APIへのデータ送信
- ユーザーへの通知メールの送信
- 商品情報のキャッシュクリア
- カスタムメタデータの保存
構文
add_action('woocommerce_update_product', 'your_custom_function', 10, 1);
パラメータ
$product_id
: 更新された商品のID。
戻り値
このアクションフックには戻り値はありません。
使用可能なプラグインWooCommerceのバージョン
- WooCommerce: 2.1.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_update_product', 'log_product_update', 10, 1);
function log_product_update($product_id) {
global $wpdb;
$product = wc_get_product($product_id);
$wpdb->insert('your_custom_table', array(
'product_id' => $product_id,
'name' => $product->get_name(),
'updated_at' => current_time('mysql')
));
}
引用元: なし
サンプルコード2: 在庫管理システムへの通知
商品が更新された時に在庫管理システムに通知を送信します。
add_action('woocommerce_update_product', 'notify_inventory_system', 10, 1);
function notify_inventory_system($product_id) {
$product = wc_get_product($product_id);
$inventory_api_url = 'https://api.inventorymanager.com/update';
wp_remote_post($inventory_api_url, array(
'body' => json_encode(array(
'product_id' => $product_id,
'stock' => $product->get_stock_quantity()
)),
'headers' => array('Content-Type' => 'application/json'),
));
}
引用元: なし
サンプルコード3: メール通知を送信する
商品の更新時に管理者にメール通知を送信します。
add_action('woocommerce_update_product', 'send_admin_notification', 10, 1);
function send_admin_notification($product_id) {
$admin_email = get_option('admin_email');
$product = wc_get_product($product_id);
$subject = '商品が更新されました';
$message = '商品名: ' . $product->get_name() . ' が更新されました。';
wp_mail($admin_email, $subject, $message);
}
引用元: なし
サンプルコード4: キャッシュのクリア
商品情報が更新された際にキャッシュをクリアします。
add_action('woocommerce_update_product', 'clear_product_cache', 10, 1);
function clear_product_cache($product_id) {
// 商品のユニークなキャッシュIDに基づいてキャッシュを削除
$cache_key = 'product_' . $product_id;
wp_cache_delete($cache_key, 'my_product_cache_group');
}
引用元: なし
サンプルコード5: 外部APIへのデータ送信
商品情報を外部APIに送信するサンプルです。
add_action('woocommerce_update_product', 'send_to_external_api', 10, 1);
function send_to_external_api($product_id) {
$product = wc_get_product($product_id);
$api_url = 'https://example.com/api/product';
$response = wp_remote_post($api_url, array(
'body' => json_encode(array(
'id' => $product_id,
'name' => $product->get_name(),
'price' => $product->get_price()
)),
'headers' => array('Content-Type' => 'application/json'),
));
}
引用元: なし