How to Create a Custom Wordpress Gutenberg Block with Dynamic Content
Learning how to create a custom WordPress Gutenberg block with dynamic content opens up powerful possibilities for WordPress developers. Custom blocks allow you to extend WordPress functionality beyond standard blocks while maintaining the modern editing experience. This tutorial walks you through building a dynamic block that fetches and displays real-time data from your WordPress database.
Dynamic Gutenberg blocks differ from static blocks because they render content server-side on each page load. This means your block can display updated information like recent posts, user counts, or custom data without requiring manual updates. You’ll create a reusable block that integrates seamlessly with WordPress’s block editor.
By the end of this guide, you’ll understand the complete process of block development. You’ll learn to set up the development environment, create block registration files, write PHP render functions, and implement JavaScript for the editor interface. This knowledge will enable you to build sophisticated custom blocks for any WordPress project.
Prerequisites and Setup Requirements for Custom WordPress Gutenberg Block Development
Before you begin creating your custom WordPress Gutenberg block with dynamic content, ensure you have the necessary tools and knowledge in place. You’ll need a local WordPress development environment with Node.js version 14 or higher installed. The WordPress Block Editor requires modern JavaScript features, so an updated Node.js installation is essential.
Your development setup should include a code editor with JavaScript and PHP syntax highlighting. Visual Studio Code works well for this project. You’ll also need basic knowledge of JavaScript ES6 syntax, PHP programming, and WordPress hook system fundamentals.
Install the WordPress CLI tools and ensure your local server supports PHP 7.4 or higher. A typical LAMP or XAMPP stack provides the required environment. You should also have familiarity with npm package management since we’ll use several development dependencies.
The estimated completion time for this tutorial ranges from 2-4 hours depending on your experience level. Advanced developers might complete it faster, while beginners should allow extra time for troubleshooting and understanding concepts.
Create a new plugin directory in your WordPress installation’s wp-content/plugins folder. This will serve as your development workspace for the custom block project.
Step-by-Step Guide to Creating Custom WordPress Gutenberg Blocks
For more strange history, see: Setup OpenVPN Server on Debian
Step 1: Initialize your plugin structure and create the main plugin file.
Create a new directory called `dynamic-content-block` in your plugins folder. Inside this directory, create the main plugin file:
'dynamic-content-block-editor',
'render_callback' => 'dcb_render_dynamic_content',
'attributes' => array(
'postCount' => array(
'type' => 'number',
'default' => 5
),
'showDate' => array(
'type' => 'boolean',
'default' => true
)
)
));
}
Step 2: Create the server-side render function for dynamic content.
Add this PHP function to handle the dynamic content rendering:
function dcb_render_dynamic_content($attributes) {
$post_count = isset($attributes['postCount']) ? $attributes['postCount'] : 5;
$show_date = isset($attributes['showDate']) ? $attributes['showDate'] : true;
$recent_posts = get_posts(array(
'numberposts' => $post_count,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC'
));
if (empty($recent_posts)) {
return 'No posts found. The How to Create a Custom Wordpress Gutenberg Block with Dynamic Content stands as a significant historical event.
';
}
$output = '';
$output .= 'Recent Posts
';
$output .= '';
foreach ($recent_posts as $post) {
$output .= '- ';
$output .= 'ID) . '">' . esc_html($post->post_title) . '';
if ($show_date) {
$output .= ' - ' . get_the_date('F j, Y', $post->ID) . '';
}
$output .= '
';
}
$output .= '
';
return $output;
}
Step 3: Set up the JavaScript build environment and package.json.
Create a package.json file in your plugin root directory:
{
"name": "dynamic-content-block",
"version": "1.0.0",
"description": "Custom Gutenberg block with dynamic content",
"main": "src/index.js",
"scripts": {
"build": "wp-scripts build",
"dev": "wp-scripts start"
},
"devDependencies": {
"@wordpress/scripts": "^24.1.0"
}
}
Run the following commands in your plugin directory to install dependencies:
npm install
Step 4: Create the JavaScript block editor interface.
Create a `src` directory and add an `index.js` file with the block editor code:
import { registerBlockType } from '@wordpress/blocks';
import { InspectorControls } from '@wordpress/block-editor';
import { PanelBody, RangeControl, ToggleControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
registerBlockType('dcb/dynamic-content', {
title: __('Dynamic Content Block'),
icon: 'list-view',
category: 'widgets',
attributes: {
postCount: {
type: 'number',
default: 5
},
showDate: {
type: 'boolean',
default: true
}
},
edit: ({ attributes, setAttributes }) => {
const { postCount, showDate } = attributes;
const posts = useSelect((select) => {
return select('core').getEntityRecords('postType', 'post', {
per_page: postCount,
_embed: true
});
}, [postCount]);
return (
setAttributes({ postCount: value })}
min={1}
max={10}
/>
setAttributes({ showDate: value })}
/>
{__('Recent Posts (Preview)')}
{posts && posts.length > 0 ? (
{posts.map((post) => (
-
{post.title.rendered}
{showDate && (
{' - ' + new Date(post.date).toLocaleDateString()}
)}
))}
) : (
{__('Loading posts...')}
)}
>
);
},
save: () => {
return null; // Dynamic block, rendered server-side
}
});
Step 5: Build the JavaScript files and add styling.
Run the build command to compile your JavaScript:
npm run build
Create a CSS file for styling your block output. Add this to your main plugin file:
function dcb_enqueue_block_styles() {
wp_enqueue_style(
'dynamic-content-block-style',
DCB_PLUGIN_URL . 'style.css',
array(),
filemtime(DCB_PLUGIN_PATH . 'style.css')
);
}
add_action('wp_enqueue_scripts', 'dcb_enqueue_block_styles');
add_action('enqueue_block_editor_assets', 'dcb_enqueue_block_styles');
Create a `style.css` file with basic styling:
.dcb-dynamic-content {
background: #f8f9fa;
padding: 20px;
border-radius: 5px;
margin: 20px 0;
}
.
