我正在使用ACF's update_sub_field函数将循环中的内容添加到子转发器字段。
我已经达到了将数据添加到子中继器的地步,但是它覆盖了自身。它只会更新子中继器的第一行,因此我只会看到最后一个循环。
我正在使用$counter
迭代父转发器,但是当我尝试向子转发器添加迭代时,它将中断该功能。像这样:
update_sub_field( array($field_key, $counter, $sub_field_key, $rowcount), $value, $post_id );
我尝试了另一个功能add_sub_row
...这会向子中继器添加正确的行数,但不会添加数据。
这是我的完整代码:
// Product Code Titles
$rows = $html->find('div[class=product-table]', 0)->find('tr');
$field_key = "field_5ae0882f9d6f9";
$sub_field_key = "field_5ae088999d6fb";
if(empty($rows)){
die("Empty array");
}
$titles = array(); // aka your $data
// here we fetch the first row and iterate to get titles
$row = current($rows);
foreach ($row->find('td') as $cell) {
$titles[] = array("column_title" => strip_tags($cell->innertext));
}
update_field( $field_key, $titles, $post_id );
// here we continue iteration starting from second row
$value = array();
$rowcount = 1;
while($row = next($rows)){
$cells = $row->find('td');
$columnsCount = count($cells);
$counter = 1;
foreach ($cells as $cell) {
$value[] = array("text" => strip_tags($cell->innertext));
update_sub_field( array($field_key, $counter, $sub_field_key), $value, $post_id );
echo '<pre>'; print_r($value); echo '</pre>';
$value = array();
$counter++;
}
$rowcount++;
}
仅提供一些上下文,我正在将表数据放入子转发器字段中来重新创建该表。
答案 0 :(得分:0)
关于这个主题的知识并不多,希望对其他人有帮助。
我停止了将其追加到$value
数组中,将函数更改为update_sub_row
,并添加了一个计数器来迭代子中继器行。
这是完整的代码:
// Product Code Titles
$rows = $html->find('div[class=product-table]', 0)->find('tr');
$field_key = "field_5ae0882f9d6f9";
$sub_field_key = "field_5ae088999d6fb";
if(empty($rows)){
die("Empty array");
}
$titles = array(); // aka your $data
// here we fetch the first row and iterate to get titles
$row = current($rows);
foreach ($row->find('td') as $cell) {
$titles[] = array("column_title" => strip_tags($cell->innertext));
}
update_field( $field_key, $titles, $post_id );
// here we continue iteration starting from second row
$value = array();
$rowcount = 1;
while($row = next($rows)){
$cells = $row->find('td');
$columnsCount = count($cells);
$counter = 1;
foreach ($cells as $cell) {
$value = array("field_5ae088b79d6fc" => strip_tags($cell->innertext));
update_sub_row( array($field_key, $counter, $sub_field_key), $rowcount, $value, $post_id );
echo '<pre>'; print_r($value); echo '</pre>';
$value = array();
$counter++;
}
$rowcount++;
}