Support

Account

Home Forums General Issues Programmatically Creating Records Containing a Repeater

Helping

Programmatically Creating Records Containing a Repeater

  • I have a custom post type that has a field group associated with it. One of the fields is a repeater. I set up a form on the site so end-users could submit and populate this custom post type in the back-end.

    I am doing this by first creating a post using $post_id = wp_insert_post($lo, false); and then populating fields using

    
    if ($post_id > 0) {
     add_post_meta($post_id, 'first_name', $_POST['firstName']);
     ...
     ...
    

    For the repeater, I read in the documentation to use add_row() so I tried the following with no luck. In my form, I have the option to add 4 social links using
    a dropdown select named social_network[] containing values like Facebook, Instagram, etc and a social_network_url[] containing the corresponding Facebook or Instagram URL

    
    if ( count($social_network) > 0 && count($social_network_url) > 0 ) {
          foreach ($social_network as $key => $value) {
    
            $link = array(
            	'social_network'=> $value,
            	'url'	=> $social_network_url[$key]
            );
            add_row('social_media_Links', $link, $post_id);
          }
        }
    

    The $social_network and $social_network_url variables come from

    
      $social_network = $_POST['social_network'];
    
      $social_network_url=array_filter($_POST['social_network_url'],function( $item ){
        return !is_null( $item ) && !empty( $item ) && strlen( trim( $item ) ) > 0 && $item!='';
      });
    
    
  • Using add_post_meta() will only work with an ACF field if it is a simple type of field. This means anything listed under “Basic” field types. You should be using update_field() and using the field key to update all ACF fields, as explained here https://www.advancedcustomfields.com/resources/update_field/ to ensure that the fields are created correctly.

    Adding content to a repeater can be done the same way. Let say for example that the field key of the repeater is “field_1”, and the sub fields are “field_2” for network and “field_3” for url.

    
    // construct an array for the repeater value
    $value = array(
      // each row is a nested array
      array(
        // row 1
        // each row contains field key => value pairs for the fields
        'field_2' => 'name of network',
        'field_3' => 'url value'
      ),
      array(
        // row 2
        'field_2' => 'name of network',
        'field_3' => 'url value'
      ),
      // etc for each row
    );
    // update the repeater
    update_field('field_1', $value, $post_id);
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Programmatically Creating Records Containing a Repeater’ is closed to new replies.