概要
woocommerce_product_bulk_edit_save
アクションフックは、WooCommerceの管理画面において、一括編集処理が保存される際に呼び出されます。このフックは、特に商品情報の一括編集に関連する機能を実装する際に非常に便利です。
このアクションは、以下のような機能を実装する際によく使われます:
- 商品メタデータのバルク更新
- カスタムフィールドの一括編集
- 在庫状況の一括変更
- 価格や割引の一括適用
- 商品のステータス(公開/非公開)の一括変更
- タグやカテゴリーの一括追加/削除
構文
do_action( 'woocommerce_product_bulk_edit_save', $product_ids );
パラメータ
$product_ids
(array): 一括編集対象の商品のIDの配列。
戻り値
このアクションには戻り値はなく、カスタム処理を実行するために使用されます。
使用可能なプラグインWooCommerceのバージョン
このフックはWooCommerceのバージョン3.0以上で利用可能です。
ワードプレスのバージョン
WordPressのバージョン4.0以上で使用できます。
サンプルコード
サンプルコード1: カスタムフィールドの一括更新
このコードは、一括編集中に「custom_field」カスタムフィールドを更新するサンプルです。
add_action( 'woocommerce_product_bulk_edit_save', 'update_custom_field_bulk_edit' );
function update_custom_field_bulk_edit( $product_ids ) {
if ( isset( $_POST['custom_field'] ) ) {
foreach ( $product_ids as $product_id ) {
update_post_meta( $product_id, 'custom_field', sanitize_text_field( $_POST['custom_field'] ) );
}
}
}
サンプルコード2: 商品の価格を一括更新
このサンプルでは、一括編集時に対象の商品全体の価格を一括で変更します。
add_action( 'woocommerce_product_bulk_edit_save', 'bulk_edit_product_price' );
function bulk_edit_product_price( $product_ids ) {
if ( isset( $_POST['new_price'] ) ) {
foreach ( $product_ids as $product_id ) {
update_post_meta( $product_id, '_price', sanitize_text_field( $_POST['new_price'] ) );
update_post_meta( $product_id, '_regular_price', sanitize_text_field( $_POST['new_price'] ) );
}
}
}
サンプルコード3: 一括で在庫管理の設定を変更
このコードは、一括編集で在庫管理の設定を有効または無効にするサンプルです。
add_action( 'woocommerce_product_bulk_edit_save', 'update_product_stock_management' );
function update_product_stock_management( $product_ids ) {
$manage_stock = isset( $_POST['manage_stock'] ) ? 'yes' : 'no';
foreach ( $product_ids as $product_id ) {
update_post_meta( $product_id, '_manage_stock', $manage_stock );
}
}
サンプルコード4: カテゴリーの一括変更
このコードは、一括編集時に商品のカテゴリーを変更するサンプルです。
add_action( 'woocommerce_product_bulk_edit_save', 'bulk_edit_product_category' );
function bulk_edit_product_category( $product_ids ) {
if ( isset( $_POST['product_categories'] ) ) {
$categories = array_map( 'intval', $_POST['product_categories'] );
foreach ( $product_ids as $product_id ) {
wp_set_object_terms( $product_id, $categories, 'product_cat' );
}
}
}
サンプルコード5: 商品ステータスの一括変更
このコードは、一括編集で商品ステータス(例えば、「公開」や「非公開」)を変更するサンプルです。
add_action( 'woocommerce_product_bulk_edit_save', 'bulk_edit_product_status' );
function bulk_edit_product_status( $product_ids ) {
if ( isset( $_POST['product_status'] ) ) {
$status = sanitize_text_field( $_POST['product_status'] );
foreach ( $product_ids as $product_id ) {
wp_update_post( array( 'ID' => $product_id, 'post_status' => $status ) );
}
}
}
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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 |