WordPress became the world’s largest CMS platform for a bunch of reasons. However, the main reason is certainly the way it can be enhanced with both plugins or code.

Most people working for building WP websites nowadays are web designers, rather than fullstack or PHP devs. No problem here, and some of them already use top-notch frontend tools which avoid JS/CSS bloat or redundancy.

Unfortunately, when it comes to create or tweak themes or plugins, add new widgets or components or any other development task involving CSS, people not just forget about good practices, but also ignore some of WP not-so-obvious functions.

For those who add CSS on template files

You are just wrong. You could either register and enqueue assets for more control, or even use tools like Grunt or Gulp to build your themes and plugins. But no, if you add CSS directly on template files or even inside HTML tags (given you are not using something like Tailwind), then you should be building websites on Geocities, not WP.

Start by learning the WP codex for assets and stop doing such thing. Pretty please. While programming for WP or any other CMS or content management platform, assets and dependencies must be properly managed, not just sprinkled over the HTML. Even for SEO purposes it is key in these days.

For those doing the right thing

And by the right thing I mean enqueing assets. If you got WP basics for themes and templates, then you know functions like wp_register_style or wp_enqueue_style, which is good.

However, just by taking a look on themes used by clients, we constantly notice that most web designers are still overlooking some other tools provided by WP codex. And one of them is the function wp_add_inline_style.

Of course one could argue that his theme enqueues a dozen of CSS files depending on the template. So, given a certain condition, he is enqueing or not stylesheets here and there. If just WP had a tool for conditionally add CSS declarations to an existent file…

Well, that’s exactly what wp_add_inline_style does. Having a CSS previously registered, one may apply any conditions and just add new CSS declarations to that file, without the need of register any other file.

The mechanism is stupidly simple. One could just write any sort of rules and conditions, adding or removing new CSS declarations to an array or concatenated string – and once it is finished, add to the main stylesheet.

// Considering there is a 'existent'style' stylesheet already registered.

function additional_css()
{
  $css = [];
  $post_id = get_the_ID();
  
  // Hide posts with an even ID number from archive pages.
  if(($post_id % 2) == 0 && is_archive()) {
    $css[] = 'post-' . $post_id;
  }

  $to_add = implode(',', $css) . ' { display: none; }';

  wp_add_inline_style('existent-style', $css);
}

add_action('wp_enqueue_scripts', 'additional_css');