Day 8: Creating Dynamic Gutenberg Blocks

Introduction

Welcome to Week 2 of the 30-day Gutenberg development series! In this week, we’ll focus on more advanced block development topics, starting with dynamic blocks.

Dynamic Gutenberg blocks allow you to fetch and display content that changes depending on the data available. This could be data from WordPress (like recent posts, categories, or users) or external sources using APIs.

In this article, we’ll walk through the process of creating a simple dynamic block that displays the latest blog posts from WordPress. By the end of this tutorial, you’ll have the foundational knowledge to build more complex blocks that fetch and display dynamic content.

What Are Dynamic Blocks?

Dynamic blocks render their content dynamically based on the data that is available when the page is viewed. Unlike static blocks, which store their content directly in the post or page’s HTML, dynamic blocks pull data when the block is rendered, either from WordPress itself or from external sources.

Some common use cases for dynamic blocks include:

  • Displaying recent posts, categories, or comments.
  • Showing user-specific data, like the current user’s name or profile info.
  • Fetching external data from APIs (e.g., displaying weather data, stock prices, etc.).

Step 1: Creating a Dynamic Block

Let’s create a dynamic Gutenberg block that displays the latest blog posts from your WordPress site.

Step 1.1: Setting Up the Block Files

Create a new folder for your block, for example:
wp-content/themes/your-theme/blocks/latest-posts/

Inside this folder, create the following files:

  • block.json (metadata for your block)
  • index.js (JavaScript to define the block’s behavior)
  • latest-posts.php (PHP file to render dynamic content)

Step 1.2: Defining Block Metadata in block.json

In your block.json, add the following metadata:

{
    "apiVersion": 2,
    "name": "your-theme/latest-posts",
    "title": "Latest Posts",
    "category": "widgets",
    "icon": "admin-post",
    "description": "A block that displays the latest blog posts.",
    "supports": {
        "html": false
    },
    "editorScript": "file:./index.js",
    "render": "file:./latest-posts.php"
}

Explanation:

  • apiVersion: 2: This specifies that we’re using the latest version of the Block API.
  • render: This points to the PHP file (latest-posts.php) that will dynamically generate the content for this block.

Step 2: Fetching Latest Posts Using PHP

Now, we’ll create the latest-posts.php file to dynamically fetch the latest blog posts using WordPress functions.

Here’s how to fetch and display the latest 5 posts:

<?php

function render_latest_posts_block($attributes, $content) {
    // Query for the latest posts
    $recent_posts = wp_get_recent_posts(array(
        'numberposts' => 5, // Number of posts to display
        'post_status' => 'publish',
    ));

    // Start the output
    $output = '<div class="latest-posts-block">';

    if (!empty($recent_posts)) {
        foreach ($recent_posts as $post) {
            $output .= '<h3><a href="' . get_permalink($post["ID"]) . '">' . esc_html($post["post_title"]) . '</a></h3>';
            $output .= '<p>' . get_the_excerpt($post["ID"]) . '</p>';
        }
    } else {
        $output .= '<p>No recent posts found.</p>';
    }

    $output .= '</div>';

    return $output;
}

// Register the dynamic block with the render callback
register_block_type('your-theme/latest-posts', array(
    'render_callback' => 'render_latest_posts_block',
));

Explanation:

  • wp_get_recent_posts(): This WordPress function retrieves the latest posts. We’re fetching 5 published posts here.
  • get_permalink() and get_the_excerpt(): These functions retrieve the post’s URL and excerpt, respectively, to display them in the block.
  • register_block_type(): This registers the block and uses the render_callback function to dynamically generate the block’s content.

Step 3: Defining the Block in JavaScript (index.js)

In your index.js file, you’ll define how the block appears in the editor.

import { registerBlockType } from '@wordpress/blocks';
import { __ } from '@wordpress/i18n';

registerBlockType('your-theme/latest-posts', {
    title: __('Latest Posts', 'your-theme'),
    description: __('Displays the latest blog posts.', 'your-theme'),
    icon: 'admin-post',
    category: 'widgets',
    edit: () => {
        return <p>{__('This block displays the latest posts on the front end.', 'your-theme')}</p>;
    },
});

Explanation:

  • edit: Since the block is dynamic and the content is generated on the server (PHP), we’re only displaying a placeholder message in the editor that informs users what the block will do on the front end.

Step 4: Testing the Dynamic Block

To test your dynamic block:

  1. Rebuild the Block: Run the following command to build the block if you’re using a bundler like @wordpress/scripts:
npm run start
  1. Add the Block to a Post:
    • Go to the WordPress dashboard and create a new post or page.
    • Insert the “Latest Posts” block.
    • The block will display a placeholder in the editor but will show the latest posts on the front end.
  2. Publish and View the Front End: Once published, view the front end of your post/page to see the block dynamically display the latest blog posts.

Step 5: Enhancing the Dynamic Block

You can enhance the dynamic block further by:

  • Adding Settings: Use InspectorControls to allow users to configure the number of posts to display or select a category to filter the posts.
  • Styling: Add custom CSS or inline styles to the block’s PHP output to ensure it looks great on the front end.
  • Fetching External Data: You can fetch data from external APIs (e.g., displaying weather data, social media feeds) using PHP’s wp_remote_get() function.

Here’s a quick example of allowing users to select how many posts to display:

// Update the PHP code to handle a custom number of posts
function render_latest_posts_block($attributes, $content) {
    $numberposts = isset($attributes['numberposts']) ? $attributes['numberposts'] : 5;

    $recent_posts = wp_get_recent_posts(array(
        'numberposts' => $numberposts,
        'post_status' => 'publish',
    ));

    // The rest of the code remains the same
}

Conclusion: The Power of Dynamic Blocks

Dynamic Gutenberg blocks offer immense flexibility, allowing you to pull in content and data dynamically, either from your WordPress site or external sources. By using dynamic blocks, you can build features like recent posts, testimonials, or real-time content updates, making your WordPress site more interactive and engaging.

In Day 9, we’ll take a closer look at custom block attributes and how they interact with dynamic content, giving you even more control over block behavior.

External Links:

Provide a link to the WordPress Block API documentation for additional reference on dynamic blocks.


Leave a Reply

Your email address will not be published. Required fields are marked *