Often times you would want to add just a little layout tweak to a certain page or a post. A custom call to action, or a fancy background image for the hero area and so on.

One would tend to add these small tweaks to the global WordPress theme CSS file. You may think that a couple of extra lines of CSS here and there in the main file won’t make any difference. But in time they WILL add up, increase CSS file size and create code bloat and confusion.

Besides, theme’s main CSS file is ALWAYS a load blocking resource in Google’s page speed evaluation. So you should fight for every Kb. That is why it is better to add page specific CSS rules ONLY to the page or post they refer to, instead of adding them to the theme CSS file to be loaded everywhere.

Here are the step by step instructions for adding page- or post-specific CSS to your WordPress theme

ACF setup

  1. Install the free version of ACF plugin and activate it.
  2. Go to Custom Fileds -> Field Groups (left side menu) and click Add New button.
  3. Enter a title. For example: Custom CSS.
  4. In Location Rules leave the default: Post type || is equal to || Post. Then click Add rule group button and set it to Post type || is equal to || Page. Leave the rest of the setting as is.
  5. Click the blue Add field button. Enter field name, e.g. Custom CSS (group and field name can be the same) and set field type to Text area.
    NB: do not use WYSIWYG editor field type, it will insert unwanted html tags in your CSS. Text area is the best option.
  6. Click Publish.

Page and post editing screens

Now a custom field will appear on each page or post editing screen. It will be below the main Gutenberg/Classic editor. And may be in between some other panels, like YOAST. page revisions, excerpt, etc. This is how it look in Prowebdesign back-end:
Custom CSS field WordPress theme

Insert you custom CSS there. If you are using new classes, do not forget to add them to the page elements in the main editor or template.

Template code

Open your theme’s header.php template and add the following code somewhere after <?php wp_head(); ?>

<?php 
$custom_css = get_field('custom_css');            
if( !empty($custom_css) ){?>
<style><?php echo $custom_css; ?>
</style>
<?php }?>

Take care to use the correct custom field slug! I have named my field Custom CSS, so the slug is custom_css. If you named your field differently, you will have a different slug. Check for slug value in Field Name in the custom CSS ACF group:

Now the custom CSS code you insert into Custom CSS field on individual pages or posts will show up in the <head> section of these pages or posts.