概要
woocommerce_ajax_save_product_variations
は、WooCommerce内で製品のバリエーションデータを非同期的に保存するためのフックです。このアクションは、以下のような機能を実装する際によく使用されます。
- 製品のバリエーションの追加や編集の処理
- バリエーション価格や在庫の動的更新
- バリエーション属性の変更
- バリエーションの順序変更
- カスタムフィールドの付加
- ユーザーインターフェースの拡張
構文
do_action( 'woocommerce_ajax_save_product_variations', $post_id );
パラメータ
$post_id
: 保存するバリエーションに関連する製品の投稿ID。
戻り値
このアクション自体は値を戻しませんが、アクションにフックされた関数が実行されることにより、製品バリエーションの保存が行われます。
使用可能なプラグインバージョン
- 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_ajax_save_product_variations', 'custom_save_product_variations', 10, 1 );
function custom_save_product_variations( $post_id ) {
// バリエーションの在庫データを更新
if ( isset( $_POST['variation_stock'] ) ) {
update_post_meta( $post_id, '_stock', sanitize_text_field( $_POST['variation_stock'] ) );
}
}
このサンプルコードは、製品のバリエーションが保存される際に、在庫データを更新します。
サンプルコード2
add_action( 'woocommerce_ajax_save_product_variations', 'custom_update_variation_price', 10, 1 );
function custom_update_variation_price( $post_id ) {
// バリエーションの価格を設定
if ( isset( $_POST['variation_price'] ) ) {
update_post_meta( $post_id, '_price', sanitize_text_field( $_POST['variation_price'] ) );
}
}
このサンプルコードは、バリエーションが保存される際に新しい価格を設定します。
サンプルコード3
add_action( 'woocommerce_ajax_save_product_variations', 'custom_modify_variation_attributes', 10, 1 );
function custom_modify_variation_attributes( $post_id ) {
// 製品バリエーションの属性を更新
if ( isset( $_POST['variation_attributes'] ) ) {
$attributes = array_map( 'sanitize_text_field', $_POST['variation_attributes'] );
update_post_meta( $post_id, '_product_attributes', $attributes );
}
}
このサンプルコードは、バリエーションが保存される際に属性情報を更新します。
サンプルコード4
add_action( 'woocommerce_ajax_save_product_variations', 'custom_save_custom_fields', 10, 1 );
function custom_save_custom_fields( $post_id ) {
// カスタムフィールドを保存
if ( isset( $_POST['custom_field'] ) ) {
update_post_meta( $post_id, '_custom_field', sanitize_text_field( $_POST['custom_field'] ) );
}
}
このサンプルコードは、製品バリエーションが保存される際に特定のカスタムフィールドを保存します。
サンプルコード5
add_action( 'woocommerce_ajax_save_product_variations', 'custom_reorder_variations', 10, 1 );
function custom_reorder_variations( $post_id ) {
// バリエーションの順序を更新
if ( isset( $_POST['variation_order'] ) ) {
$order = array_map( 'intval', $_POST['variation_order'] );
update_post_meta( $post_id, '_variation_order', $order );
}
}
このサンプルコードは、バリエーションが保存される際に、その順序を更新します。