Support

Account

Home Forums ACF PRO Get first of layout 'type' in Flexible Content

Solving

Get first of layout 'type' in Flexible Content

  • Hey Elliot & Team,

    I am using flexible content, and have several layouts available. One layout is called “visual_editor.” Since visual editor will not necessarily be the first layout chosen, I was hoping to find a way to get the first instance of “visual_editor”, if it exists.

    The reason is that I would like to be able to use that data to create an excerpt on a different page. Is this possible?

  • Hi @jrstaatsiii,

    Thank you for sharing the solution. I will now copy the same to this forum so that it can help out a fellow dev in future:

    <?php
    /*
     * Returns the first instance of a given layout option
     * @param - $id - the id of the post you are trying to target: '' by default
     * @param - $fc_field - the name of the ACF flexible field: 'content_blocks' as the default
     * @param - $fc_layout - the name of the flexible content layout: 'visual_editor' as the default
     * @return - mixed
     * @todo - test different types of returned content. at the moment, I am only using this for returning a string
    */
    function get_first_instance_of_content_block( $id = '', $fc_field = 'content_blocks', $fc_layout = 'visual_editor' ) {
    	
    	if ( class_exists('acf') ) { 
    	
    		if ( have_rows( $fc_field, $id ) ) { 
    		
    			$content_blocks = get_field( $fc_field, $id );
    			$content = array();
    		
    			foreach ( $content_blocks as $block ) {
    				if ( $block['acf_fc_layout'] == $fc_layout ) {
    					$content[] = $block[$fc_layout];
    				}
    			}
    		
    			reset($content);
    		
    			return $content[0];
    	
    		}
    	
    	} else {
    		
    		return '<p class="error">Advanced Custom Fields is required for <code>get_first_instance_of_content_block()</code> to work.</p>';
    		
    	}
    	
    }
  • How do you use this code?
    I added it to my fuctions.php and changed the $fc_field and $fc_layout variables to match mine, but how do I use it in my index.php loop? Do I need to call the function? Nothing happens when I add it to my functions file.

    I’m currently having to manually add an excerpt via the “except field”- <?php the_excerpt_max_charlength( 400 ); ?>

    Any help appreciated.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Get first of layout 'type' in Flexible Content’ is closed to new replies.