How to create a Dynamic Block in WordPress

Creating a block, can be daunting and it get’s worse when you don’t know were to start or see there is a lot to do. However, you can easily start creating you blocks using @wordpress/create-block1

To start creating a block in WordPress, you’ll need to have Node.js and npm installed on your system. Node.js is a JavaScript runtime, and npm (node package manager) is a package manager for JavaScript. You can download both from the official Node.js website.

After you’ve installed Node.js and npm, you will install @wordpress/create-block globally in your development environment.

$ npm install -g @wordpress/create-block

By default, a Block, after being customized, generates static code that is, stored in the database. However, there are cases where we need to use dynamic content. Lucky us, @wordpress/create-block has that covered too, and I will show you how to do it in this post.

At the end of this tutorial, you will have a working block that displays the updated Bitcoin rates by reading the data from a public API.

Here’s the final result.

Scaffolding the Block Plugin

In wp-content/plugins folder, create a block-ready plugin. This will install @wordpress/scripts2 among other required config and source code files.

$ npx @wordpress/create-block bitcoin --variant dynamic

Can take some time, but once it’s ready, change to the newly created folder and start @wordpress/scripts

$ cd bitcoin
$ npm start

Now is the time to activate the plugin to test it and ensure it’s working as expected. Let’s create a new page (I named it: Bitcoin today) and add the Bitcoin Block.

We are using the scaffolded code, so, you should see the standard output.

Let’s write some code

The final output will be a table, therefore, we need to add some styles to make it look nice. We want to be looking the same in the editor and the page. Add the following styles to src/editor.css and src/style.css.

.wp-block-create-block-bitcoin {
  table {
    border: 1px solid #dedede;
    border-bottom: none;
    border-collapse: collapse;
  }

  th {
    font-weight: 700;
    background-color: #f1f1f1;
  }

  th,
  td {
    text-align: left;
    padding: 4px 8px;
    border-bottom: 1px solid #dedede;
    font-size: 0.875rem;
  }
}

In src/render.php replace the current code with this one. It’s the file used to display the output for the page containing the block.

<div <?php echo get_block_wrapper_attributes(); ?>>
	<?php

	$url     = "https://api.coindesk.com/v1/bpi/currentprice.json";
	$request = wp_remote_get( $url );
	$code    = wp_remote_retrieve_response_code( $request );

	if ( is_wp_error( $request ) || $code !== 200 ) {
		echo 'Error: Unable to retrieve and parse JSON data.';

		return;
	}

	$api_data = wp_remote_retrieve_body( $request );
	$data = json_decode( $api_data, true );

	$bpi = $data['bpi'];

	echo "<table class='rates'>";
	echo "<tr><th>Currency Code</th><th>Rate</th></tr>";
	foreach ( $bpi as $currency => $info ) {
		$code = $info['code'];
		$rate = $info['rate_float'];
		echo "<tr><td>$code</td><td>$rate</td></tr>";
	}
	echo "</table>";
	?>
</div>

Locate src/edit.js and add ServerSideRender support. Ensure it looks like in the code below. ServerSideRender will display the same output printed in src/render.php, once the block is added. The block prop attribute is required to identify which block’s content should be displayed.

import ServerSideRender from '@wordpress/server-side-render';

export default function Edit( props ) {
	return (
		<p { ...useBlockProps() }>
			<ServerSideRender block={props.name}></ServerSideRender>
		</p>
	);
}

In the already created page, remove the Bitcoin block, Save, reload the page, and the same block again. This will ensure any modification will be loaded properly.

Your block is now ready and working. Every time you reload the page, the rates will be updated as well according to the data loaded from the API.

There many features, we can add, like toolbars, settings in the inspector, and attributes. You can even make the block updates automatically every few seconds, to mimic a real-time update. For that and more, keep checking the new posts I will be publishing in the future.

Footnotes

  1. Create Block is an officially supported tool for scaffolding a WordPress plugin that registers a block. It generates PHP, JS, CSS code, and everything you need to start the project. It also integrates a modern build setup with no configuration. @wordpress/create-block ↩︎
  2. This is a collection of reusable scripts tailored for WordPress development. For convenience, every tool provided in this package comes with an integrated recommended configuration. packages-scripts
    ↩︎