概要
woocommerce_process_$POST->POST_TYPE_meta
は、WooCommerceプラグイン内で、特定のカスタム投稿タイプ(例えば、製品や注文)に関連するカスタムフィールドのデータを保存する際に使用されるフックです。このアクションは、ユーザーが投稿タイプのメタデータを処理や保存をする際に、実行されます。
このアクションは、次のような機能を実装する際に特によく利用されます。
1. 製品のカスタムメタデータの保存
2. 定期購入商品の設定
3. 商品のプロモーション情報の保存
4. 注文メモやカスタムフィールドの追加
5. ユーザーの選択したオプションの保存
6. 支払い情報や配送先情報の拡張
構文
add_action('woocommerce_process_post_meta', 'my_custom_save_meta', 10, 2);
パラメータ
$post_id
: 保存対象の投稿ID$post
: 保存されている投稿オブジェクト
戻り値
このアクションは戻り値を持ちません。
使用可能なプラグインバージョン
- WooCommerce バージョン: 3.0.0以上
使用可能なWordPressバージョン
- WordPress バージョン: 4.0以上
サンプルコード
サンプル 1: 製品メタデータの保存
このサンプルは、製品のカスタムメタデータを保存します。
add_action('woocommerce_process_product_meta', 'save_custom_product_meta', 10, 2);
function save_custom_product_meta($post_id, $post) {
if (isset($_POST['_custom_field'])) {
update_post_meta($post_id, '_custom_field', sanitize_text_field($_POST['_custom_field']));
}
}
引用元: https://docs.woocommerce.com/
サンプル 2: 特定のカスタム商品の情報を処理
この例では、特定のカスタムフィールドの値を保存します。
add_action('woocommerce_process_product_meta', 'save_order_notes', 10, 2);
function save_order_notes($post_id) {
if (isset($_POST['order_notes'])) {
update_post_meta($post_id, 'order_notes', sanitize_textarea_field($_POST['order_notes']));
}
}
引用元: https://www.businessbloomer.com/
サンプル 3: 定期購入商品のメタデータの保存
このサンプルでは、定期購入商品のメタデータを保存する方法を示します。
add_action('woocommerce_process_product_meta_subscription', 'save_subscription_meta', 10, 2);
function save_subscription_meta($post_id) {
if (isset($_POST['_subscription_price'])) {
update_post_meta($post_id, '_subscription_price', sanitize_text_field($_POST['_subscription_price']));
}
}
引用元: https://docs.woocommerce.com/
サンプル 4: 商品のプロモーション情報の保存
この例では、商品のプロモーション情報を保存します。
add_action('woocommerce_process_product_meta', 'save_promotion_info', 10, 2);
function save_promotion_info($post_id) {
if (isset($_POST['_promotion_info'])) {
update_post_meta($post_id, '_promotion_info', sanitize_textarea_field($_POST['_promotion_info']));
}
}
引用元: https://www.businessbloomer.com/
サンプル 5: ユーザーが選択したオプションの保存
このサンプルは、ユーザーが選択したオプションを保存します。
add_action('woocommerce_process_product_meta', 'save_user_selected_options', 10, 2);
function save_user_selected_options($post_id) {
if (isset($_POST['user_options'])) {
update_post_meta($post_id, 'user_options', array_map('sanitize_text_field', $_POST['user_options']));
}
}
引用元: https://woocommerce.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 |