Search code examples
phpwordpressadvanced-custom-fieldsacfpro

Insert repeater rows in flexible content programmatically


As the title suggests, I have this kind of structure:

flexible_content (Flexible content)
-accordion (Layout)
--accordion_item (Repeater)
---title (text)
---content (wysiwyg)

I have a external database from which I want to insert a number of accordions. How can I do that programmatically with PHP? I have created a loop after getting the data from DB and want to run insert functionality inside the loop.
I added the "accordion" layout manually. Now I want to add the accordions inside. I tried with add_rows and update_field, but could not do it successfully.
Here is the code attempt:

foreach ($posts as $key => $value) {

        $field_key = "field_5cab37b5c28y6"; // flexible_content field key
        $value = array(
            array( "content" => $value['content'], "acf_fc_layout" => "accordion" ),
            array( "title" => $value['title'], "acf_fc_layout" => "accordion" ),
        );
        update_field( $field_key, $value, $post_id );
    }

Solution

  • I managed to find out a way to do this. Here is my code:

    <?php
    $wp_page_id = 745;
    
    //I have a table of data which I got from another non-wordpress site
    $external_page_id = "247";
    $sql = "SELECT data FROM `DataObject` WHERE `parent` = '$external_page_id' AND `public` = '1'";
    $mydata = $wpdb->get_results($sql);
    
    if ( !empty($mydata) ) {
    
        $fc_data = array(
            'flexible_content_field_key'          => 'field_5dbc1c6d966de',
            'flexible_content_layout'             => 'accordion',
            'flexible_content_repeater_field_key' => 'field_5dc52a904eb2b',
        );
    
        // making the array of data for repeater fields inside flexible content
        $tmp = array();
    
        foreach ($mydata as $key => $value) {
            $json = json_decode( $value->data, true );
    
            $data_to_insert = array(
                'field_5dc52aa64eb2c' => $json['title'], // title field in repeater
                'field_5dc52ae44eb2d' => $json['accordion-content'] // content field in repeater
            );
    
            array_push($tmp, $data_to_insert);
        }
    
        // got final array of all repeater field data. Now putting it into the final array of data
        $fc_data['data_to_insert'] = $tmp;
    
        // making the final array of data
        $fc_rows = array(
            array(
                'acf_fc_layout' => $fc_data['flexible_content_layout'],
                $fc_data['flexible_content_repeater_field_key'] => $tmp
            )
        );
    
        // now insert the array of data
        update_field($fc_data['flexible_content_field_key'], $fc_rows, $wp_page_id);
    }