Search⌘ K
AI Features

PHP Render Callback Approach

Explore the PHP render callback approach to dynamically render WordPress blocks. Learn to shift output from JavaScript to PHP, enabling seamless updates without manual edits across multiple posts or templates.

In this lesson, we will delve deeper into the concept of block outputs and how they are saved. We will begin by discussing the issue that arises when we change the HTML structure for the save function or the attributes of our block type. As we have seen in the previous lessons, this causes a problem and we run into the "Attempt Block Recovery" message. We will explain why this happens and explore ways to modify our code to prevent this from occurring.

This error message occurs because WordPress needs to trust the saved text to extract values from it using source and selector properties. If the HTML structure of the save function changes, the selector may not select the same value, and hence, the trust is broken.

Now imagine, if we used a block in ten different templates or in hundreds of blog posts and we needed to make a change in the save component. This would entail manually updating each and every template and blog post to remove the "Attempt Block Recovery" error.

We can work around this problem by allowing WordPress to figure things out on its own by changing the HTML structure. We will demonstrate how this can be achieved in our code.

Deprecated property

To provide WordPress with a history of how to make changes, we can add a new top-level property called deprecated to our code.

There are several ways to go about it. We can simply create a deprecated property when registering the block type in index.js. Or we can create a separate file called deprecated.js and import it in index.js.

The deprecated property should be an array of objects, with each object containing the attributes and saved values from the previous version of our code. The objects in the deprecated array can have the following properties:

  • attributes ...