Adding your own classes to WordPress blocks

The HTML tags (e.g. div, main) in a WordPress (WP) template file must have a WP class, such as wp-block-group, wp-block-query or wp-block-query-pagination. If you add another class to these willy-nilly, your site editor and post editor will break, showing you the dreaded invalid HTML error.

It seems that the HTML tag must be ‘primed’ by telling the surrounding template markup tags that the HTML tags have non-native classes. To do this, add your class, say it’s called post-metadata, to the markup tag as {"className":"post-metadata"} – a little block of JSON – inside the opening markup tag (between its name and the closing angle bracket), then add the class name to the HTML tag as normal:

<!-- wp:group {"className":"post-metadata"} -->
  <div class="wp-block-group post-metadata">
<!-- /wp:group -->

Adding your own class will allow you to specify which of the many divs of class wp-block-group you mean when it comes to adding the theme’s CSS styles.

A note on WP block theme class names

The class names seem to start with a verb, typically is or has and describe either a property of the class or the class itself. For example:

We all know that maintainable HTML and CSS use classes that are semantic – that is, they describe their purpose, not their styling. It must be easy to change the styling without having to change the name of the class. A class that styles headings but is named after the colour is going to look pretty foolish being called sky-blue-pink-with-yellow-dots when the colour changes to green. A class called html is always going to be relevant to the styling of HTML code, although its colour may change from purple to blue at some point.

However, these WP classes describe the styles themselves. What happens when dull lavender is no longer wanted as a background colour? The theme author must go through all the template files and change the class name to something else, perhaps has-vivid-lavender-background-color or has-dull-lilac-background-color. What if the background is no longer required at all? Think of all those has-background classes that will have to be removed!

The theme author is encouraged to use these non-semantic names in themes.json, which, as far as I can gather, is intended to provide the end-user with a means of styling the site, within the confines of the theme.

This use of non-semantic class names seems to be a backward step: we’re supposed to have moved away from class names such as red and alignleft; something WP seems yet to do.

I can’t tar all block themes with the same brush: not all class names used are non-semantic, and not all themes use non-semantic class names. I will endeavour to use semantic names as far as I can in developing Panda-Puss and any future themes I create.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.