As of WordPress 6.7, core WordPress blocks with a heading level dropdown include support for the levelOptions
attribute. This applies to the Heading, Site Title, Site Tagline, Query Title, Post Title, and Comments Title blocks. The levelOptions
attribute accepts an array of numbers corresponding to heading levels, where 1
represents H1, 2
represents H2, and so on.
This attribute allows you to specify which heading levels should appear in the dropdown UI, providing a lightweight curation method that does not require block deprecations. Any existing heading levels are preserved in the markup, while `levelOptions` only affects the UI display.
In the following code snippet, H1, H5, and H6 heading levels are disabled in the Heading block for all users except those with the edit_theme_options
capability (typically Administrators). This approach helps prevent content creators from unintentionally adding multiple H1 elements or applying specific heading levels not intended for use.
<?php
function devblog_modify_heading_levels_globally( $args, $block_type ) {
// Check if the current user is an Administrator.
$is_administrator = current_user_can( 'edit_theme_options' );
// Only proceed if the current block is a Heading and the user is not an Administrator.
if ( 'core/heading' !== $block_type || $is_administrator ) {
return $args;
}
// Disable H1, H5, and H6.
$args['attributes']['levelOptions']['default'] = [ 2, 3, 4 ];
return $args;
}
add_filter( 'register_block_type_args', 'devblog_modify_heading_levels_globally', 10, 2 );
You can add this code to your theme’s functions.php
file or a custom plugin. Once applied, here’s what the end result looks like in the Editor.
Props to @areziaal and @bph for reviewing this snippet and providing feedback.
Leave a Reply