Wordpress Page ID CSS Generation

How to Generate Dynamic CSS for Each Page ID in WordPress

Explains how to dynamically generate CSS for each page ID, class, and more in WordPress using PHP and JavaScript.

Shou Arisaka
2 min read
Oct 17, 2025

This article explains how to dynamically generate CSS for each page ID, class, and more in WordPress using PHP and JavaScript.

How to Generate Dynamic CSS for Each Page ID in WordPress

The first thing that comes to mind is directly manipulating PHP.

Theme Customizer - Dynamic CSS PHP File - WordPress Development Stack Exchange

Hmm, I’m not quite sure. I often do something similar in bash where I generate Python or Ruby files with here documents, execute them from bash, and receive the output - a kind of metaprogramming. This is somewhat similar to the current topic, but when dealing with sites with high traffic like blogs, doing I/O operations repeatedly would likely get warnings from the rental server, so it’s better not to do it…

So I thought about using JavaScript to read HTML and generate CSS.

WordPress generates classes in HTML tags, especially in the body tag.

For example, the body of a post page is:

<body class=“post-template-default single single-post postid-1521 single-format-standard oceanwp-theme sidebar-mobile default-breakpoint has-sidebar content-right-sidebar post-in-category-programming has-topbar has-breadcrumbs” itemscope=“itemscope” itemtype=“http://schema.org/WebPage”>

The body of the homepage is:

<body class=“home blog oceanwp-theme sidebar-mobile default-breakpoint has-sidebar content-right-sidebar has-topbar has-breadcrumbs” itemscope=“itemscope” itemtype=“http://schema.org/WebPage”>

The idea is that you can get information from these classes, similar to PHP functions like is_post or is_home.

So specifically, it looks like this:

$(document).ready(function(){

  if ( document.querySelector('body').classList.contains('home') ){

    var css = document.createElement("style");
    css.type = "text/css";
    css.innerHTML = `
    h2 {
        font-size: 20px !important;
        font-weight: bold !important;
    }

    a {
        font-weight: 100;
    }
    `;
    document.body.appendChild(css);

  }

});

With this, you can add CSS that you want to apply only to the homepage.

Recently, even HTML generated with JavaScript seems to have high priority in terms of SEO, so this should be fine.

I just found this and it looks useful:

PHP in CSS file? - WordPress Development Stack Exchange

Share this article

Shou Arisaka Oct 17, 2025

🔗 Copy Links