Using WordPress ‘block_version()’ PHP function

The block_version() WordPress PHP function returns the current version of the block format that the content string is using. If the content string doesn’t contain blocks, it returns 0.

Usage

To use block_version(), you’ll need to pass a string of content to the function. Here’s an example:

$content = "This is a test string";
$version = block_version($content);
echo $version;

In this case, since the $content string doesn’t contain any blocks, the output will be 0.

Parameters

  • $content (string): This is the content you want to test. It’s required to run the function.

More Information

See WordPress Developer Resources: block_version()

The block_version() function is a part of WordPress’ Gutenberg block editor, and it was implemented in WordPress version 5.0.

Examples

Checking a String Without Blocks

$content = "Hello, world!";
$version = block_version($content);
echo $version; // Outputs: 0

This example checks a basic string without any blocks. The output is 0, meaning no blocks are used.

Checking a String With a Single Block

$content = "<!-- wp:paragraph -->Hello, world!<!-- /wp:paragraph -->";
$version = block_version($content);
echo $version; // Outputs: 1

This code tests a string containing a single WordPress block. The output is 1, which means the block is in version 1 format.

Checking a String With Multiple Blocks

$content = "<!-- wp:paragraph -->Hello, world!<!-- /wp:paragraph --><!-- wp:image -->Image Block<!-- /wp:image -->";
$version = block_version($content);
echo $version; // Outputs: 1

In this example, the string contains multiple blocks. The output is 1, since all blocks are in version 1 format.

Checking a String With a Version 2 Block

$content = "<!-- wp:paragraph {"version":2} -->Hello, world!<!-- /wp:paragraph -->";
$version = block_version($content);
echo $version; // Outputs: 2

Here, the string contains a block using version 2 format. The output from block_version() reflects this.

Checking a String With Mixed Version Blocks

$content = "<!-- wp:paragraph -->Hello, world!<!-- /wp:paragraph --><!-- wp:image {"version":2} -->Image Block<!-- /wp:image -->";
$version = block_version($content);
echo $version; // Outputs: 2

In this final example, the string has blocks of different versions. The output is the highest version number among the blocks, which is 2 in this case.