Correct way to enqueue page specific CSS file

So this way a CSS file would be enqueued in the header.php and then another in that specific page.php.

No because:

  • all the things that get enqueued are processed in the header but you’re calling it after the header has already been done. The cat has already gotten out of the bag, the horse has already bolted, the order matters. At best this will push the CSS to the footer instead
  • This would add the CSS to every single page

Instead, you’re already using body_class() and that function is there for a reason, so add the CSS everywhere and use the classes from that function to target just the pages you want. This way you don’t need a separate file or weird PHP logic, it just works. E.g. post archives has a archive class as well as others, ranging from generic classes such as post to single to single-post postid-1067, as well as other utility classes such as wether the user is logged in, or the specific template file ( single-post-template ). These exist for all pages WordPress can serve ( if body_class is used ).

A conditional enqueue is neither necessary or optimal here unless the file you’re enqueing is especially large.

But if you insist, you can grab the post ID outside the loop and wrap your enqueue in an if statement using $id = get_queried_object_id();. Note that this can also return user IDs or term IDs if you’re on an author archive or a category archive for example, so pay attention to the functions such as is_singular() or is_archive()

Also, if your styling blocks then use block.json to specify the stylesheets and scripts for the frontend. If you do this, WordPress will automatically enqueue those files but only when that block is used.