Home Forums Add-ons Flexible Content Field Get content of layout as an array


Get content of layout as an array

  • I have pages with flexible content. I identify layouts in my loop and then include a template file for that layout. These template files are set up to be used in a variety of ways, from a variety of sources, and output data from an array.

    I want to get my layout data as an array, and not have to know sub-field names in advance. My current solution works, but there must be a better way?

    if ( have_rows( 'page_layout' ) ):
    		// loop through the rows of data
    	while ( have_rows( 'page_layout' ) ) : the_row();
    		if ( get_row_layout() == 'layout_1' ):
                    // get layout data as an array
                    $data = get_fields(); //get all fields for this page
                    $index = get_row_index(); // get index of current row
                    $layout_data = $data['page_layout'][$index-1];
    			include( locate_template( 'component-templates/layout-1-block.php', false, false ) );
  • No, there isn’t a better way if what you want is have an array with the data. Or maybe there isn’t, I might do it differently in order to remove an extensive if/elseif/elseif

    based on the code you provided

    // get the entire flex field
    $layouts = get_field('page_layout');
    if ($layouts) {
      foreach ($layouts as $layout_data) {
        $layout_name = str_replace('_', '-', $layout_data['acf_fc_layout']);
        $template = locate_template('component-templates/'.$layout_name.'-block.php', false, false);
        if ($template) {
          // why am I doing this?
          // if locate_template returns false, include(false) will throw an error
      } // end foreach layout
    } // end if layouts
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Get content of layout as an array’ is closed to new replies.