Support

Account

Home Forums Add-ons Flexible Content Field Count number of layout rows in flexible content field Reply To: Count number of layout rows in flexible content field

  • Actually, get_row_index() returns the index of the current row inside of the have_rows() loop and does not return the total number of rows.

    The total number of rows can be gotten like this.

    
    $number_of_rows = count(get_field('flex_field_name'));
    

    Other than looping through all of the rows and getting the layout for each, there isn’t a way to count the number of each layout used. This can be done a bit easier by getting the actual value stored for the flex field which is an array of the layouts.

    
    $layouts = get_post_meta($post_id, 'flex_field_name');
    

    this will return something like

    
    $layouts = array(
      'layout1',
      'layout2',
      'layout3',
      'layout1',
      'layout2',
      'layout3',
      'layout1',
      'layout2',
      'layout3'
    );
    

    You can then use array_count_values() to get the number of times each layout appears

    
    $layout_counts = array_count_values($layouts);
    

    this will result in another array that would look something like this

    
    $layout_counts = array(
      'layout1' => 3,
      'layout2' => 3,
      'layout3' => 3
    );