Support

Account

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

Helping

Count number of layout rows in flexible content field

  • The get_row_index() (https://www.advancedcustomfields.com/resources/get_row_index/) function outputs how many rows there are in i flexible content field. Is there a equivalent function for outputting the number of times a specific layout is used?

  • 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
    );
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Count number of layout rows in flexible content field’ is closed to new replies.