Get and Post repeating Fields correctly, persisting the order

This code sample shows how to get and post repeating Fields in Toolset (created with Types)

Get the Fields and their order:

//We are getting a Repeating Field (MultiLine) from the Database.
//This will give us an Array() of Repeating Instances. 
$repeating_field = get_post_meta($post_id, 'wpcf-{your-field-slug}');
 
//We also need the hidden field for the above repeating Field, to determine the order wich is used for each instance (_wpcf-{your-field-slug}-sort-order)
$sort_order_repeating = get_post_meta($post_id, '_wpcf-{your-field-slug}-sort-order', true);

Update/Create Fields and their Order:

//go over all repeating fields instances
foreach ($repeating_field as $repeating_field_single_instance ) {
 
  //create a new $variable with single instance
  $single_value = $repeating_field_single_instance;
 
  //add the repeating possible answers
  add_post_meta($new_post_id, 'wpcf-{your-field-slug-new}', $single_value);
}
 
//update the order of those repeating fields
update_post_meta($new_post_id, '_wpcf-{your-field-slug-new}-sort-order', $sort_order_repeating);

This is a custom code snippet that needs to be adapted. It does NOT use public documented API, and it might change in future. We do NOT help on further custom code with this kind of data, but we show how we can get/post it

Count Repeating Field / Count multiple instances

We can achieve this by using custom shortcode. Please add this code in your theme’s or child theme’s functions.php file:


add_shortcode( 'count-repeats', 'count_repeat_func' );
function count_repeat_func($atts) {
return sizeof(get_post_meta( $atts['post-id'], 'wpcf-' . $atts['field'], false ));
}

Then you can use this ShortCode. You should wrap this ShortCode in an HTML Conditional to check if the Field does exist, as other wise unexpected results can be produced:

[count-repeats post-id="6184" field="url"]

More details: https://wp-types.com/forums/topic/how-to-count-repeated-field/#post-412707