Arms crossed picture of James Auble
Additional classes field in Wordpress Block Editor Inspector

Render Additional Classes in Wordpress Custom Block Render Function

PublishedNov 18th, 2022

If you're not in the process of making a custom "React" Wordpress Block than you're probably in the wrong place.

I found it really challenging to title this post for some reason, so if you've found your way here and are confused by the title, in this post is to explain how you can pass classes entered in the ADDITIONAL CSS CLASS(ES) field under Advanced in the block editor settings to a PHP render function template for your custom block.

TL;DR 

Add the following to the top of your render function template

<?php
$class_name = 'wp-block-my-block';
if (!empty($attributes['className'])) {
  $class_name .= ' ' . $attributes['className'];
}

and echo out the $class_name variable at the top-level--or wherever your want you see fit

<div class="<?php echo $class_name; ?>"> Block contents </div>

You don't need to explicitly define the className attribute, Wordpress does this for you under the hood.

It's been a while since I've said this, but code on web assassins!

Scrolldown Icon