Using the Block Bindings API to show a taxonomy count in WordPress

Yesterday, one of my clients asked me if there was a way to dynamically update a text block that showed the total number of podcast episodes. They’re using the Seriously Simple Podcasting plugin to host two separate podcast series on their website.

Every time a new episode was released, they would manually update these two text blocks:

Up until recently, the easiest way to do this was to create a custom block that would show the count. However, with the release of WordPress 6.5 we have access to the new Block Bindings API, which greatly simplifies the amount of code to accomplish this.

Seriously Simple Podcasting uses a custom taxonomy named series to assign episodes to a specific serie. Here’s how you register a block binding for each serie. This code works for any taxonomy, all you need to do is change the series text in the get_term_by function on line 2 to the slug of your taxonomy.

PHP
function get_series_count( $slug ) { $serie = get_term_by( 'slug', $slug, 'series' ); $count = $serie ? $serie->count : 0; return sprintf( _n( '%d episode', '%d episodes', $count, 'text-domain' ), $count ); } function register_block_bindings() { register_block_bindings_source( 'prefix/podcast-count', [ 'label' => __( 'Podcast Count', 'text-domain' ), 'get_value_callback' => fn ( $args ) => get_series_count( $args['series'] ), ] ); }} } add_action( 'init', 'register_block_bindings', 20 );

I’ve used priority 20 when registering the action, to make sure this hook runs after Seriously Simple Podcasting has registered their custom taxonomies.

That’s all there is to it. Now you can add the “block” to your post by pasting some code into the Code Editor view. Here’s an example for a podcast series named sample-podcast.

HTML
<!-- wp:paragraph { "metadata":{ "bindings":{ "content":{ "source":"prefix/podcast-count", "args":{ "series":"sample-podcast" } } } } } --> <p>Podcast Count</p> <!-- /wp:paragraph -->

There’s currently no UI for adding block bindings to a post, so you have to paste the above code into your post manually, but this UI will be added in a future WordPress release.

Hat tip to @remcotolsma for showing me a better to way to register the source.

Written by Daniel Post

Hi! I’m Daniel Post, a freelance full-stack WordPress developer from the Netherlands. This is my personal website, where I share articles and guides related to WordPress.

I am also available for hire, so if you’re looking for a developer for your next project feel free to get in touch!


Leave a Reply

Your email address will not be published. Required fields are marked *