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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to load a module with configuration in SCSS?SCSSCommon Table Expressions (CTE) in PostgreSQLPostgresVariables scope and shadowing in SCSS (Sass)SCSSHow to add Google Map in WordPress using ACF?WordPressHow to hide a DIV on clicks outside of it using jQuery?jQueryHow to Install PHP Laravel on MacOS Catalina?PHP