update_sub_field()


WordPressのupdate_sub_field()関数は、Advanced Custom Fields (ACF) プラグインを使用している場合に、サブフィールドの値を更新するために使用されます。

構文

update_sub_field( string $selector, mixed $value, int|string|WP_Post|null $post_id = null );

引数の説明:

  • $selector (string) — 更新するサブフィールドのフィールド名またはキー。
  • $value (mixed) — サブフィールドに設定する新しい値。
  • $post_id (int|string|WP_Post|null) — 更新対象の投稿ID。省略可能で、デフォルトでは現在の投稿。

例 1. サブフィールドの文字列値を更新

特定の投稿内のサブフィールド「description」を新しい値に更新します。

if ( have_rows('repeater_field_name') ) {
    while ( have_rows('repeater_field_name') ) {
        the_row();
        update_sub_field('description', '新しい説明');
    }
}

例 2. 数値フィールドをインクリメント

数値型のサブフィールド「count」を1ずつ増加させます。

if ( have_rows('repeater_field_name') ) {
    while ( have_rows('repeater_field_name') ) {
        the_row();
        $current_count = get_sub_field('count');
        update_sub_field('count', $current_count + 1);
    }
}

例 3. チェックボックスフィールドの値を設定

チェックボックスフィールド「options」に新しいオプション値を追加します。

if ( have_rows('repeater_field_name') ) {
    while ( have_rows('repeater_field_name') ) {
        the_row();
        update_sub_field('options', ['option1', 'option2']);
    }
}

例 4. サブフィールド内の条件付き値を更新

サブフィールド「status」の現在の値が「pending」の場合、「approved」に更新します。

if ( have_rows('repeater_field_name') ) {
    while ( have_rows('repeater_field_name') ) {
        the_row();
        if ( get_sub_field('status') === 'pending' ) {
            update_sub_field('status', 'approved');
        }
    }
}

例 5. 投稿IDを指定して値を更新

特定の投稿(投稿IDを取得する関数を使用)内のサブフィールド「rating」を更新します。

$post_id = get_the_ID();
if ( have_rows('repeater_field_name', $post_id) ) {
    while ( have_rows('repeater_field_name', $post_id) ) {
        the_row();
        update_sub_field('rating', 5, $post_id);
    }
}

注意事項

  • リピーターフィールドのループ内で使用する必要があります。
  • データを安全に更新するため、正しい$selectorを指定してください。