How to Add CSS to Block Editor Based on Post Type
I have multiple post types on my website, for example you’re reading a normal post, but there are also support articles like this one. The posts are almost similar except one thing – the heading font size.
It is quite easy to change the title font size depending on a post type on a website, you just have to make sure that your theme is using body_class() function and then you can use a CSS selector like .single-{post type} h1, but this way will never work in Gutenberg! So please don’t try to add classes via admin_body_class or anything like this.
Let’s assume that we have style-editor.css file which contains the block editor styles for all post types and we have style-editor-custom-h1.css which contains you know what.
And here is the code:
add_action( 'after_setup_theme', function() {
add_theme_support( 'editor-styles' );
add_editor_style( 'style-editor.css' );
if(
false !== stristr( $_SERVER[ 'REQUEST_URI' ], 'post-new.php' ) && isset( $_GET[ 'post_type' ] ) && 'support' === $_GET[ 'post_type' ]
|| false !== stristr( $_SERVER[ 'REQUEST_URI' ], 'post.php' ) && 'support' === get_post_type( $_GET[ 'post' ] )
) {
add_editor_style( 'style-editor-custom-h1.css' );
}
} );Now let me explain how it works.
- We are using
$_SERVER[ 'REQUEST_URI' ]global variable in order to check what page is currently displaying, we can not useget_current_screen()here because it is not defined at this moment. - I also decided to use
after_setup_themeaction hook because it is originally used for Gutenberg configuration likeadd_theme_support()functions etc (yes, I know we are currently moving on totheme.jsonfile). You can probably find other recommendations over the internet to usepre_get_postshook in order to gain the access to global$postvariable, so you can omit usingget_post_type()function, but you know what, good practice code for me is more important, just one more SQL request, which is, for the only page in admin area is totally ok, anyway some plugins most people use like ACF doesn’t care about it at all, you will have tens of SQL request which could be avoided.
Misha Rudrastyh
Hey guys and welcome to my website. For more than 15 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
Hi. I’m trying to follow this code. Please tell me, How does the if statement need to change if I only want to do add_editor_style() for the extra CSS file if I am editing a post (not a page or other custom post type)? Thank you!
Hi, you just need to change the post type name from
supporttopostin the code above.