0

I would like to add a body class to my WordPress pages which should be usable to identify pages/posts/categories... I would then want to save that identifier class in the database and be able to add unique CSS code only to that specific page (no matter if it is a post/page/category/tag/archive etc.)

What I have thought so far without success:

  • Use get_the_ID() for posts and pages, but what about all the other pages like archives, category pages, tag pages etc.? Are there even ways for every kind of content to get a unique ID?
  • Store the URL, but what happens once the user changes the permalink of a page / post or the domain?
  • Get all currently available body classes of a page and combine them to create a CSS selector, but what happens if another class is added or a class is removed?

Does anyone have a different approach?

  • ID means identificator. It is unique. You can get the post ID or taxonomy (category, tag, custom taxonomy) ID. The ways you get it are not even, but there are functions to get the ID for any type. URL is subject to change, so, do not rely on it. – Max Yudin Jun 9 '17 at 11:23
2

Everything in WP has an ID. As long as your theme is using body_class you probably already have built-in classes that will cover your scenario.

For example:

  • Pages will include a page-id-## class, where ## is the id specific to that particular page.
  • The homepage will include a home class and if it's your main blog archive also a blog class.
  • Posts and custom post types will include a postid-## class, where ## is the id specific to that particular post/CPT.
  • Categories will include a category-## class, where ## is the id specific to that particular post.

So, you should be able to use built-in functionality to identify content. All your theme has to do is, in header.php, use body_class like this:

<body <?php body_class(); ?>>
| improve this answer | |
  • Ok thank you, I just thought there must be a simpler way to identify a specific page other than checking whether there is one of many possible classes in it. – phpheini Jun 10 '17 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.