What is the advantage of ‘register_block_type’ (the PHP function) when creating custom blocks?

1.: The register_block_type lets you load additional stylesheets and scripts for your block in the frontend

2.: As you yourself wrote, register_block_type lets you define a dynamic php render_callback function

3.: If you use a render_callback, you can of course use filters within it.

EDIT: As the comments pointed out, there is some clarification needed on how to use custom filters

Firstly, you can make the whole function pluggable just by wrapping it into a function_exists like this

...
'render_callback' => 'my_awesome_block_render'));

if(!function_exists('my_awesome_block_render')){
  function my_awesome_block_render($attributes,$context){
      //whatever
  }
}

Secondly: Filters.

WordPress filters are an interesting thing. The long and short is the following: Whenever you call $var =apply_filters('my_cool_filter_name',$var);, WordPress looks into its global filter function array if a function is registered for the filter “my_cool_filter_name”. So for using a custom filter, you just think of a name that hopefully isn’t taken by any other plugin/function and apply_filters to it.

So, to use filters to change some aspects of your blocks render, you just use apply_filters with whatever you wish. Let’s have an example with a slider block:

function my_awesome_slider_block_render_function($attributes){
//do whatever stuff you want
$slider_speed = apply_filters(‘my_awesome_slider_block_slider_speed’,$attributes[‘slider_speed’]);
//whatever else
}

if nobody added a filter to “my_awesome_slider_block_slider_speed”, the variable $slider_speed contains now $attributes[‘slider_speed’].

However, if for some reason you need to change this speed, (let’s say, you use a child theme for mobile devices and the slider should be slower on mobile devices), you can just add a filter in your functions.php like this:

add_filter('my_awesome_slider_block_slider_speed','change_the_mobile_speed');
function change_the_mobile_speed($slider_speed){
  return 800;
}

The same works for actions, too.

Happy Coding!

Leave a Comment