Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

ACF: How to programmatically Update Flexible Content Field? WordPress

  • SOLVED

I want to be able to create sub fields inside a flexible content field.

My setting is this one:

menu_item_field is a flexible content field that contains:

1.1 menu_item_parent (text)
1.2 menu_item_child (repeater field)
1.2.1 menu_item_child_title (text)
1.2.2 menu_item_child_text (text)
1.2.3 menu_item_child_img (repeater field)
1.2.3.1 menu_item_child_img_item (img)

This is the structure that results of the above setting:

Group One
Item 1 title
Item 1 description
Item 1 img 1
Item 1 img 2
Item 2 title
Item 2 description
Item 1 img 1
Item 1 img 2

So far I've been able to insert only the Group field and I wanted to know if it's possible to do more complex stuff.

I did it using:


add_row(
'menu_item_field', [
'acf_fc_layout' => 'menu_item',
'menu_item_parent' => 'Test',
], $postID)


The above code returned only the main group titles ie:


Group One
Group Two


I know there's update_sub_row() but I haven't been able to successfully use it.

My main goal is to be able to edit or create new fields using a custom UI in the frontend through AJAX.

I prefer this instead of acf_form().

So, my question, is it possible to achieve what I need and what would be the proper function with the above settings.

Thanks.

Answers (3)

2020-10-05

Arnav Joy answers:

can you please share URL of your site?

2020-10-05

Hariprasad Vijayan answers:

Hi there,

Try this
// Add value to field under flexible content
add_row(
'menu_item_field',
[
'acf_fc_layout' => 'menu_item',
'menu_item_parent' => 'Test',
],
$postID
);

// Add value to repeater field under flexible content
add_sub_row(array('menu_item_field', 1, 'menu_item_child'), [
'acf_fc_layout' => 'menu_item',
'menu_item_child_title' => 'Child Title',
'menu_item_child_text' => 'Child Text',
]);

Next one is difficult, i didn't get proper solution for this. But the following solution works
// Nested repater field under Flexible content
$menu_item_field = get_field('menu_item_field');
$count = 0;
add_sub_row(array('menu_item_field_'.$count.'_menu_item_child', 1, 'menu_item_child_img'), [
'acf_fc_layout' => 'menu_item',
'menu_item_child_img_item' => 37 // Attached image ID goes here
]);

The above solution will only work when you add items first time.
update_field() and update_sub_field() canuse to update existing fields.

Try print_r(get_field('menu_item_field'));
You will get more details about how the data arranged in backend.

Please let me know if you need any more help.

Kind regards,
Hariprasad

2020-10-05

jpequens answers:

Have you tried using the actual field name?

'acf_fc_layout' => 'layout_1',
'field_5eb8743702e68' => 'test1',
'field_5eb8748302e69' => 'test2',