WPLake > Learning Hub > Using Query Loop in Gutenberg to Display ACF Fields

Using Query Loop in Gutenberg to Display ACF Fields

Utilizing Query Loop in Gutenberg for ACF fields display: Explore the functionality of Query Loop block, and WP_Query for cohesive content presentation.
query loop helps you cycle through ingredients for a particular dish

Key Points at a Glance

  1. Query Loop Block Functionality: The Query Loop block in WordPress allows you to curate and display lists of blog posts, products, or pages based on specific criteria, offering flexibility in layout design.
  2. Block Template Usage: Block Templates in WordPress enable you to maintain consistency in layout and design across their website, ensuring a cohesive presentation of content.
  3. Query Loop vs. Block Template: While the Query Loop focuses on dynamically curating and displaying specific content items, Block Templates ensure consistency in layout and design, complementing each other to create engaging content experiences.
  4. Displaying ACF Fields with Gutenberg: It provides practical guidance on displaying Advanced Custom Fields (ACF) using Gutenberg, either through a plugin like Advanced Views or via code.
  5. Querying Posts with WP_Query: You can fetch and showcase custom post-type entries associated with specific ACF fields using WP_Query, allowing for advanced customization and control over content presentation.

Table of Contents

In this post, we're going to take a deep dive into the world of the Gutenberg Blocks. Our goal is to get to know how this block works and how we can practically apply it to our projects. Plus, I'm excited to share a step-by-step guide on how to make the most of these blocks. I'll be throwing in some insights into real-life scenarios where they can shine. So, let's roll up our sleeves and explore the ins and outs of these Gutenberg Blocks!

In this tutorial we'll make use of the following plugins:
1. Advanced Views Pro (see pricing)
2. ACF Pro (see options)

What is the Query Loop block in WordPress?

In short, it's a WordPress block that lets you showcase a curated list of blog posts, products, and pages that are all related.

Using the Query Loop block is actually quite straightforward. You have the freedom to either choose from a variety of ready-to-go layouts or get creative and build your own design from scratch. Plus, the icing on the cake is that you can fine-tune how your nested blocks are displayed and give them a fully customized look that resonates with your style. It's like having the power to arrange your content exactly how you want it, without any coding fuss.

Query Loop vs. Block Template

In essence, the Query Loop and Block Template serve slightly different purposes, yet they can complement each other beautifully. The Query Loop focuses on dynamically curating and displaying specific content items, allowing you to create engaging lists or feeds. On the other hand, the Block Template ensures consistency in layout and design across your website, making it easier to manage and present your content in a cohesive manner.

Query Loop block

The Query Loop block is a tool that enables WordPress users to display a dynamic list of posts based on specific attributes. For example, it can be set to cycle through all posts of a certain category, displaying the post title and image of each one. 

This block can be quite technical to configure. As a result, beginners tend to avoid using it and instead opt for the Post List block, which is a simpler version of the Query Loop. 

While the Query Loop block is more complex, it also allows for greater flexibility. For instance, you can create a page full of your best recipes or showcase a portfolio of projects. 

Block Template

On the other hand, the Block Template is a powerful tool in WordPress that lets you design and structure your content consistently across various posts or pages. It's like setting up a blueprint for your content presentation. With a Block Template, you can define a layout, add different blocks, and ensure that your content always adheres to a specific format, which is particularly useful when you want to maintain a consistent branding or user experience.

This feature is perfect for situations where you have a set design or content structure that you want to apply to multiple pages. By creating a Block Template, you simplify the process of creating new content while maintaining a cohesive look and feel throughout your website.

In Summary:

When you combine the Query Loop and Block Template features, you can create dynamic and consistent content experiences. For example, you might use the Query Loop to display a curated list of blog posts on your homepage, and then employ a Block Template to maintain a consistent look for individual blog post pages. This way, your website remains both visually appealing and user-friendly.

Behind the Scenes

Let's break down the behind-the-scenes workings of a Query Loop block in simple terms:

Imagine you're a chef in a restaurant, and your job is to prepare dishes from a huge pantry filled with ingredients (which represent your content, like blog posts or products). Now, the Query Loop is like a magical recipe book that helps you pick and showcase specific dishes from this pantry to your customers (website visitors).

A Recipe Book should be easy to navigate.

Here's how it works:

  1. Opening the Recipe Book (Setting Criteria): You open the magical recipe book (the Query Loop block) and decide what kind of dishes you want to serve. This is where you set the criteria. For instance, you might say, "Show me all the Italian pasta dishes" or "Give me the latest dessert creations."
  2. Picking Ingredients (Fetching Content): The magical recipe book (Query Loop) goes to the pantry (your website's content storage) and gathers the dishes (content items) that match your criteria. It's like the book is doing the legwork for you and finding exactly what you're looking for.
  3. Arranging the Dishes (Displaying Content): Now, you take these selected dishes (content items) and arrange them on plates (your web page). Each dish (content item) gets its own spot. This is where you create the visual arrangement that your customers will see.
  4. Serving to Customers (Showing on Website): Voilà! You present these beautifully arranged dishes to your customers (website visitors). They get to see a customized list of content items that fit the criteria you set earlier.

Behind the scenes, the Query Loop block is like your helpful sous-chef, sorting through the pantry and presenting the dishes according to your instructions. This way, your website becomes a delightful menu of content, all thanks to the magic of the Query Loop!

Display ACF fields using Gutenberg

Now, let's explore the practical aspect of displaying the fields with Gutenberg.

Display using a plugin

Gutenberg is a powerful editor with many useful block add-ons. Fortunately, there's now a simple way to add a new Gutenberg block with custom ACF fields without the need for complex React coding. It's possible by using the plugin called Advanced Views, which introduces smart templates. You can assign fields by selecting them from a dropdown, and then paste a shortcode in the place you want to display the field output.

Let's dive in and look at more examples, of why this method is so great.

For this example we'll use Post title from the built-in posts fields, and 2 ACF fields, "Prep Time" and "Ingredients" as well as a Taxonomy called "Dish type". The Prep Time is a Number field where we'll use Minutes, and the Ingredients field is actually a Post Object field type that references the "Ingredient" Custom Post Type (CPT) items, in turn creating a relationship between Dish and Ingredient, more of this later. Finally we'll use the Taxonomy to separate our Dish posts into Types of dishes like Pasta or Desert.

Step-by-step guide

Here's a short step-by-step guide on how to create an View:

  1. Install and Activate Advanced Views Pro plugin.
    Head over to your WordPress dashboard, navigate to "Plugins," and click on "Add New." Then click "Upload Plugin", browse to the downloaded package, click Open and then "Install Now". Once uploaded and installed, activate it to enable its functionality.
  2. Create a View
    Once active, you'll find a new menu item called "Advanced Views" in your admin menu. Click on it, and then click "Add New" to create a View.
  3. Assign Fields to the View
    Within the View creation screen, you can assign fields by clicking "Add Field", you can assign multiple fields, one at a time, those from a post and the ACF fields from the field group. Choose $post$ from the Group dropdown, then select 'Title with link' from the list. Continue by adding more fields, this time choose your ACF "Group" from the dropdown, adding the ACF fields you prefer. In my case, I've added "Prep Time" number field and an "Ingredient" post object field, as well as the Taxonomy "Dish Type".
  4. Turn on Gutenberg Block (available only in ACF Pro)
    Switch to the 'General' tab and turn on "With Gutenberg Block", this will add a block for your View, and it will save it with the Name of your view.
  5. Publish the View
    Click on the "Publish" button to save and publish your View.
  6. Add View Block
    Go to your post or page and edit with Gutenberg editor, click on the "+" button and select the block that has the name of your View. Fill in the field(s) and click Publish or Update.
  7. See the results
    View the post or page to see the results.
  8. Style the output
    Use the 'CSS Code' field in the "CSS & JS" tab of your View, to insert the CSS styles.

Views Block in the Site editor

You could also add the Views Block to your Templates in the site editor. However, it's recommended to use the 'Shortcode' block with your View shortcode inside. The reason for this is that the ACF block has its own fields. These are the field values that will be displayed. If you add a block globally, the same data is displayed globally. Where the Shortcode doesn't have its own fields. It displays the fields from the current post, or from the object passed via the id argument.

gutenberg block in site edit
Add the View Gutenberg block to your post template.

Now, let's look at some PHP on how to do the same.

Display using code

First, make sure you have the ACF plugin installed and have created the necessary fields and taxonomy in your WordPress admin.

<?php
// Get the post object
global $post;

// Get the Post Title
$post_title = get_the_title();

// Get the ACF fields
$prep_time = get_field('prep_time'); // Replace 'prep_time' with the actual ACF field name
$ingredients = get_field('ingredients'); // Replace 'ingredients' with the actual ACF field name

// Get the Dish type (Taxonomy)
$dish_type = wp_get_post_terms($post->ID, 'dish_type'); // Replace 'dish_type' with the actual taxonomy name

// Check if there are dish types assigned
if (!empty($dish_type)) {
    $dish_type_name = $dish_type[0]->name;
} else {
    $dish_type_name = 'Uncategorized'; // Default if no dish type is assigned
}

// Output the information
echo '<h1>' . $post_title . '</h1>';
echo '<p>Prep Time: ' . $prep_time . ' Minutes</p>';
echo '<h2>Ingredients:</h2>';
echo '<ul>';
foreach ($ingredients as $ingredient) {
    echo '<li><a href="' . get_permalink($ingredient->ID) . '">' . get_the_title($ingredient->ID) . '</a></li>';
}
echo '</ul>';
echo '<p>Dish Type: ' . $dish_type_name . '</p>';
?>

Make sure to replace 'prep_time', 'ingredients', and 'dish_type' with the actual field names and taxonomy names you have set up in your ACF and WordPress settings. Also, you can customize the HTML structure to match your theme's design.

Place this code in your theme's template file where you want to display this information (e.g., single.php) within the WordPress loop. This code retrieves the necessary information from the post and displays it on a single post page.

Querying posts with WP_Query

The fact that we can display some ACF fields on a single post is nice and all and that is already quite a complex thing, especially if you're not familiar with writing code or where to put it, and usually, you'd want to display a list or grid of posts, and in a particular order. That's a lot of "ands's" we need.

Let's look at using the same Advanced Views Pro plugin as before, because it makes the job really easy for us non coders while keeping versatility open to coders by creating a great foundation.

Query using a plugin

Alright, we've already set up a View in which we've assigned the necessary fields, as we discussed in an earlier part of this article. Now, let's put that View to work and showcase the posts. To do this, we'll continue making use of the Advanced Views Pro plugin's Cards feature.

To follow along with this, make sure you have the following in place:

  1. A Custom Post Type, either "Recipe" or you can use the default WP Post type. In this, you should have an ACF field group that includes a "Prep Time" field as a number field and an "Ingredients" field as a post object field. Also, don't forget to include a Taxonomy named "Dish Type." You can use the built-in Categories taxonomy for this purpose.
  2. A Custom Post Type named "Ingredient" with ACF fields, particularly "Sauce" as a text-area field type.
  3. Create an ACF field group called "Heritage" with a "Origin" select field. Set the Location rules for this field group, specifying that it applies to both the 'Page' post type and the 'Ingredient' post type.

Now, let's dive in and get started.

Step-by-step guide

Here's a short step-by-step guide on how to create an ACF Card:

  1. Add a Card
    Start by visiting the Advanced Views menu, and Selecting Cards, then click "Add New".
    On the Card Edit screen, give your Card a name.
  2. Assign your View
    This is used to display every post from the query results. So if you haven't created a View yet, or you jumped to this section of the article, then first add a View and assign the fields, then come back here.
  3. Filter Post Type
    In the Post Type dropdown select "Post" or your Custom Post Type from the list.
    Note: You have options to only display 'Published' posts or to Ignore Sticky posts, but for our example, we'll leave the default options.
  4. Sort by Meta value
    In the "Sort by" dropdown, select "Meta value, and continue by choosing "Sort order" as Ascending. (We want to display our posts in alphabetical order, by Pasta Sauce Ingredient) Therefore you should now select "Ingredients" in the "Sort by Meta Field Group" and "Sauce" for the "Sort by Meta Field".
  5. Meta Filters for the query
    The idea is to only show Pasta Recipes with the Origin "Italy".
    Switch to the "Meta Filters" tab, click on "Add Rule" then "Add Field". From the Group dropdown select 'Ingredient' and then from the Field dropdown select 'Origin'. We'll keep the Comparison as 'Equal to' with Value '$post$'.
  6. Pagination made easy
    Switch to the "Pagination" tab and turn on the 'With Pagination' switch. Select whichever Pagination Type you prefer.
  7. Publish your Card
    Click "Publish" to save and publish your Card, then copy the first shortcode.
  8. Copy the shortcode into place
    Go to the page you're using to display the "Pasta dishes from Italy", add a 'Shortcode' block and paste the Card shortcode in place. Now you also need to select the "Origin" as 'Italy' for this page, now click save or update, and view your page to see the results.
  9. Style the output
    There isn't much to style on the card, but you may need to add column padding and row spacing if you're creating a grid. Or simply use the "Layout" tab to save you time.
    If you want to edit the style of the posts, then you should edit the assigned View item CSS instead.

If you don't see any posts, then make sure that you created "Ingredient" post-type items and that those fields are filled, as well as check to ensure there is "Origin" with 'Italy' selected.

Query using code

This PHP code snippet is designed to fetch and showcase "Recipe" custom post-type entries that are associated with "Ingredients" originating from Italy based on the "Origin" field. The results are presented in ascending order, sorted by the "Sauce" meta value.

<?php
$args = array(
    'post_type' => 'recipe', // Replace with your "Recipe" custom post type slug
    'meta_key' => 'sauce', // Replace with the name of the meta key used for "Sauce"
    'orderby' => 'meta_value',
    'order' => 'ASC', // Change to 'DESC' for descending order
    'meta_query' => array(
        array(
            'key' => 'ingredients', // Replace with the name of the meta key for "Ingredients"
            'value' => 'italy', // Replace with the value you want to match
            'compare' => 'LIKE', // You can use '=' or 'LIKE' based on your needs
        ),
    ),
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // Your loop code to display the posts
        the_title(); // Display the post title
        // Add more code to display post content or other custom fields
    }
} else {
    // No posts found
}

wp_reset_postdata();
?>

Make sure to replace 'recipe' with the actual slug of your "Recipe" custom post type, and replace 'ingredients' and 'sauce' with the names of the custom fields you're using for "Ingredients" and "Sauce."

Final thoughts

Learning new techniques and ideas can sometimes be challenging, but I encourage you to give it a shot. If you've chosen to explore Views or utilize plugins, you'll find that enhancing and scaling your concepts is relatively straightforward. You have the flexibility to duplicate a View or Card, customize it by adding or removing fields, and tweak Meta Filters to showcase different posts or ingredients.

Furthermore, you can take your project a step further by neatly organizing everything into a special restaurant menu. This menu (not like a website menu) would offer unique functionalities, allowing you to click on ingredients for more details on the individual post pages or access dedicated pages featuring Italian Pasta Sauce recipes.

I hope this article was useful, now go have fun and try new things.

Was this article helpful? Thank you for the feedback!

Totally useless

Slightly helpful

Very helpful

FAQ mode

/

Learning mode

  1. How does the Query Loop block work?

    The Query Loop block is a WordPress block that dynamically displays a curated list of blog posts, products, or pages based on specific criteria set by the user, providing flexibility in content presentation.

  2. What's the difference between Query Loop and Block Template?

    The Query Loop block focuses on dynamically curating and displaying specific content items, while the Block Template ensures consistency in layout and design across the website, making it easier to manage and present content consistently.

  3. What is WP_Query, and how can I use it to query posts?

    WP_Query is a WordPress class used to query posts based on specific criteria, such as post type, custom fields, or taxonomy terms. You can use it to fetch and display posts dynamically within your theme templates.

  4. How can I display Advanced Custom Fields (ACF) with Gutenberg?

    You can display ACF fields with Gutenberg either through plugins like Advanced Views or by incorporating code snippets into your themes.

Related articles

Content links (11)

About the Author

Baxter Jones

Working in the web industry for over 15 years gaining experience in design,user experience and web best practices. Has a keen eye for detail and enjoys having a process when working and creating. He thinks WordPress is the best thing since sliced bread and when he’s not behind his computer he’ll be in the garden.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly

    Got it