Yogesh Chauhan's Blog

WordPress: How to display fields from ACF Flexible Contents?

in WordPress on May 23, 2021

One of the most versatile option Advanced Custom Fields (ACF) has is Flexible Contents. You can create all sort of things with it and it gives you much more control in creating a dynamic webpage.

Here are couple of screenshots from ACF Official Flexible Contents page.

A Flexible Content field that allows you to choose a layout
List of field settings shown when setting up a Flexible Content field

Let’s try to print each field from the image above step by step.

First of all, you need to check if there is any contents in flexible contents field. Here’s how to do that:



// Check if the flexible content value exists.
if( have_rows('content') ):
...
...
endif;


If so, we need to use while loop to go through each flebile blocks:



// Check if the flexible content value exists.
if( have_rows('content') ):

    // Loop through rows.
    while ( have_rows('content') ) : the_row();
      ...
      ...
    endwhile;

...
...
endif;


Now, we need to check each and every case for our desired layout and get the variables or print them.



// Check if the flexible content value exists.
if( have_rows('content') ):

    // Loop through rows.
    while ( have_rows('content') ) : the_row();

        // Case: Paragraph layout.
        if( get_row_layout() == 'paragraph' ):
            $text = get_sub_field('text');
            echo '<p class="para">' . $text . '<p>';

        // Case: Download layout.
        elseif( get_row_layout() == 'download' ): 
            $file = get_sub_field('file');
            // Do something...

        endif;

    endwhile;

...
...
endif;


You can add group or a repeater blocks instead of simple variables too.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Casting in PostgreSQLPostgresWordPress: How to loop through a repeater field in ACF?WordPressHow to render lists inside a component in React?ReactHow to check if the element exists using JavaScript and jQuery?JavaScript@forward rule in SCSS (Sass)SCSSHow to zoom an element on hover using CSS?CSS