Lesson 5.2. A Custom Block for the Store

Goal

Create a dynamic block that shows product data and works inside Product Collection.

Key concepts

  • @wordpress/create-block — a block scaffold with a build
  • block.json: render: file:./render.php — server render, always fresh data
  • usesContext: ["postId"] — the block gets the product ID from the template or the collection
  • render.php has $attributes, $content, $block; get_block_wrapper_attributes()
  • Block attributes — settings in the inspector (InspectorControls)

Diagram

flowchart LR
  ED["Editor<br/>edit.js — preview"] --> SAVE["save: null"]
  SAVE --> DB[("post_content:<br/><!-- wp:my/stock-badge /-->")]
  DB --> R["render.php<br/>wc_get_product( postId )"]
  R --> HTML["Badge HTML<br/>for every product"]

Code

block.json:

JSON
{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "my/stock-badge",
  "title": "Stock badge",
  "category": "woocommerce",
  "usesContext": [ "postId" ],
  "attributes": {
    "threshold": { "type": "number", "default": 5 }
  },
  "supports": { "html": false, "color": { "background": true, "text": true } },
  "textdomain": "my-plugin",
  "editorScript": "file:./index.js",
  "style": "file:./style-index.css",
  "render": "file:./render.php"
}

render.php:

PHP
<?php
$product_id = $block->context['postId'] ?? get_the_ID();
$product    = $product_id ? wc_get_product( $product_id ) : null;

if ( ! $product || ! $product->managing_stock() ) {
	return;
}

$qty       = (int) $product->get_stock_quantity();
$threshold = (int) ( $attributes['threshold'] ?? 5 );

if ( $qty <= 0 || $qty > $threshold ) {
	return;
}
?>
<p <?php echo get_block_wrapper_attributes( [ 'class' => 'stock-badge' ] ); ?>>
	<?php
	/* translators: %d: items left */
	echo esc_html( sprintf( _n( 'Only %d left', 'Only %d left', $qty, 'my-plugin' ), $qty ) );
	?>
</p>

Registration:

PHP
<?php
add_action( 'init', static function () {
	register_block_type( __DIR__ . '/build/stock-badge' );
} );

Common mistakes

SymptomCauseFix
In Product Collection the block shows the same product every timeIt uses get_the_ID() instead of the contextusesContext and $block->context['postId']
The badge is stale after the stock changesA static block (save with HTML)Dynamic render through render.php
The block "broke" in the editor after a markup changeThe save() of a static block changed without deprecatedA dynamic block or deprecated

Weak and strong answer

Question: A static or a dynamic block for a stock badge?

Weak answer. Static — it's simpler.

Strong answer. Dynamic. The stock changes without editing the page, so the HTML has to be generated at request time. A static block would store the number in post_content forever. I take postId from the context so the block works both in the product template and in Product Collection.

Why the second is stronger: The candidate picks the block type by the nature of the data and remembers the context.

Practice

In the terminal: generate the dynamic stock-badge block with create-block, look at what's in src and build, build it and activate the plugin.

On your own site: turn the block into a stock badge with the code above and add a threshold attribute with a slider in the inspector. Insert the block into the Product Template inside Product Collection.

npm / wp — Module 5. A Custom Store Block

Interview Questions

When the data changes independently of content editing: prices, stock, user data, post lists. Then render.php generates the HTML on every request.

A way to pass data from a parent block to its children: providesContext on the parent, usesContext on the child. Product Template passes the postId of every product.

It adds the classes and styles from supports (colors, spacing, alignment) to the block wrapper. Without it the inspector settings don't reach the markup.

Save your progress

Sign in or create a free account to mark lessons as completed and continue the whole course. You will come back to this lesson.