概要
update_row
関数は、WordPress のプラグイン Advanced Custom Fields (ACF) における特定の行のデータを更新するために使用される関数です。この関数は、既存の Repeater または Flexible Content フィールド値のデータ行を更新します。以下のような機能を実装する際に特によく使われます:
- フィールドグループ内のデータを動的に変更する。
- ユーザー入力によるカスタムデータを保存・更新する。
- 一括更新処理を行い、特定の条件に基づいたフィールドの値を変更する。
- 管理画面でのフォーム送信後にデータを整理する。
- 外部ソースからインポートしたデータをACFに保存する。
- 定期的にデータを更新するスクリプトを作成する。
構文
update_row( $field_key, $row_index, $value, $post_id );
パラメータ
$field_key
(string): 更新を行うフィールドのキー(slug)。$row_index
(int): 更新対象の行のインデックス(0から始まる)。$value
(mixed): 更新する値。$post_id
(int): 更新対象の投稿のID。
戻り値
- 成功した場合は
true
、失敗した場合はfalse
を返します。
使用可能なACFバージョン
- バージョン 5 以降で使用可能。
使用可能なWordPressバージョン
- WordPress 4.0 以降で使用可能。
サンプルコード
サンプルコード1: Repeaterフィールドの特定行を更新
$field_key = 'field_123abc'; // Repeaterフィールドのキーを指定
$row_index = 0; // 最初の行を指定
$value = array( 'sub_field_1' => '新しい値' ); // 更新するサブフィールドの値
$post_id = 456; // 更新対象の投稿ID
update_row( $field_key, $row_index, $value, $post_id );
このコードは、特定の投稿にある Repeater フィールドの最初の行のサブフィールドを新しい値で更新します。
サンプルコード2: Flexible Contentフィールドの行を更新
$field_key = 'field_abc456'; // Flexible Contentフィールドのキーを指定
$row_index = 1; // 2番目の行を指定
$value = array( 'sub_field_2' => '更新されたデータ' ); // 更新するサブフィールドの値
$post_id = 789; // 更新対象の投稿ID
update_row( $field_key, $row_index, $value, $post_id );
このコードは、Flexible Content フィールドの 2 番目の行のデータを更新します。
サンプルコード3: Repeaterの複数行更新
$field_key = 'field_123abc'; // Repeaterフィールドのキーを指定
$post_id = 456; // 更新対象の投稿ID
$rows = get_field( $field_key, $post_id ); // 現在の行を取得
foreach ($rows as $index => $row) {
$row['sub_field'] = '新しい値 ' . ($index + 1); // 新しい値を設定
update_row( $field_key, $index, $row, $post_id ); // 更新を実行
}
このコードは、指定した Repeater フィールドのすべての行を順次更新します。
サンプルコード4: 特定のサブフィールドを更新
$field_key = 'field_xyz123'; // フィールドキー
$row_index = 0; // 最初の行を指定
$value = array( 'sub_field_name' => '特定の値' ); // 更新するサブフィールドの値
$post_id = 101; // 更新対象の投稿ID
update_row( $field_key, $row_index, $value, $post_id );
このコードは、特定の Repeater フィールド内の最初の行のサブフィールドを更新します。
サンプルコード5: 空の行を削除して更新
$field_key = 'field_abc999'; // フィールドキー
$post_id = 303; // 更新対象の投稿ID
$rows = get_field( $field_key, $post_id ); // 現在の行を取得
if ( ! empty( $rows ) ) {
foreach ( $rows as $index => $row ) {
if ( empty( $row['sub_field_to_check'] ) ) {
unset( $rows[$index] ); // 空の行を削除
}
}
update_field( $field_key, $rows, $post_id ); // 更新を実行
}
このコードは、空のサブフィールドを含む行を削除し、残りのデータを更新します。
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 | 〇 |