WordPress 5.0 introduced a number of new block-related functions which super-charge developers with new tools to leverage the new Gutenberg WordPress block editor. Let’s take a look at one of those neat functions.
Determine if post has a specific block
First up, let’s dive into the
has_block function, introduced in WordPress 5.0. This function ultimately determines whether a post, or content string, contains a specific block type – based on the block name. It accepts two parameters:
$block_type– Name of the block we’re looking for
$post– Post content/id/object, which defaults to global $post
Below you’ll find the
has_block` function in it’s simplest form:
It’s important to note that a block’s name is the unique identifiable string registered for the block. Names are structured as
namespace/block-name, where namespace is the name of the block plugin (or
core, if you’re targeting a block within WordPress core).
You can learn more about block names and complete block registration on the official Gutenberg Handbook. If you’re just getting into block development, this handbook will be your best friend – bookmark it.
Conditionally load block front-end scripts
One of the best use cases I see for
It’s important to note that this only currently works on singular pages/pages — not in the context of any blogroll (index, archive, search, etc.) templates. I’m not exactly sure why it doesn’t, but I have opened up an issue on GitHub to spread awareness on the issue/get some further insight.