YogeshChauhan . com

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.

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to include CSS and JavaScript files in your WordPress plugin?WordPressWhat are Controlled Components in React?ReactCurrencyPipe in Angular 9 with ExamplesAngularPHP arrays for US states’ full names and abbreviationsPHP3 JavaScript methods to use when you want to go back and forth in historyJavaScriptLearn to Establish Connection using MySQLi (object-oriented), MySQLi (procedural) and PDO with Example CodePHP