首页 > 解决方案 > 提交表单总是复制 ACF 子字段的第一行

问题描述

我创建了一个表单,我正在尝试使用ACF 的update_field函数用数据更新子字段。

我有一个带有子字段的转发器字段 - “时间”,“发布者”和“评论”。

目前它正在将数据添加到提交时的子字段中......问题是它总是将它添加到第一行。我怎样才能确保它添加了一个新行?

<form action="#" id="form" method="get">
  <input type="text" id="forum-comment" name="forum-comment">
  <input type="submit" name="submit" value="Submit">
</form>

<?php
// Check if form was submitted
$value = array();
if(isset($_GET['submit'])){
  $comment = $_GET['forum-comment'];
  $time = date('d/m/Y g:i a', time());

  global $current_user;
  get_currentuserinfo();

  // Comments
  $id = get_the_id();
  $field_key = "field_5c90d272c7ca9";

  $value[] = array(
    "time"          => $time,
    "posted_by"     => $current_user->ID,
    "comment"           => $comment,
  );

  update_field( $field_key, $value, $id );
}

标签: phpadvanced-custom-fields

解决方案


如果这对任何人有帮助,@04FS 指出:

<?php
// Check if form was submitted
$value = array();
if( have_rows( 'comments' ) ):
  while( have_rows( 'comments' ) ): the_row();
    $time = get_sub_field( 'time' );
    $posted = get_sub_field( 'posted_by' );
    $comment = get_sub_field( 'comment' );

    $value[] = array(
      "time"        => $time,
      "posted_by"       => $posted,
      "comment"         => $comment,
    );

  endwhile;
endif;

if(isset($_GET['submit'])){
  $comment = $_GET['forum-comment'];
  $time = date('d/m/Y g:i a', time());

  global $current_user;
  get_currentuserinfo();

  // Comments
  $id = get_the_id();
  $field_key = "field_5c90d272c7ca9";

  $value[] = array(
    "time"          => $time,
    "posted_by"     => $current_user->ID,
    "comment"           => $comment,
  );

  update_field( $field_key, $value, $id );
}
?>

推荐阅读