I have a template that is used for many different sections of my site (About, News, etc.). The nav bar needs to show a little graphic arrow below the section you're in. I was passing this via the template:

$page = 'about';

...but then I realized that won't work since the template file I was editing is used for a bunch of different sections, not just 'about'.

So I need something on the 'page' interface screen where I can somehow indicate the page that the user is on. Some ideas for solutions:

  • Idea #1: does WordPress would set some kind of class on the 'body' tag to indicate the page you're on (like if it generated a slug based on the page name and added that as a class to the body tag)? Then just do everything I need to do in CSS without complicating things.
  • Idea #2: some kind of built-in field on WordPress's 'page' admin that would let my header know what page it is on.
  • Idea #3: I could make copies of my template for each major section. Very stupid way to go about it.

I would REALLY prefer to not go the whole extra-fields route, manually adding a metadata field to my pages, pulling it from the db on page load, etc. That seems like super overkill for just having a way to let my template code identify what page it is being used on.


Idea #1 is correct if your template use body_class() like

<body <?php body_class(); ?>>

In this case the body tag will be something like:

<body class="page page-id-6 page-template-default">

If the id of viewed page is 6 and template used is the default.

See Codex

However, in pages the global $post variable is available even in the header and before calling the_post(). So $post->post_name will contain the slug of your page and you can make use of it as you want.

| improve this answer | |
  • How frustrating that it doesn't also add a class based on the slug-- i.e. "page-about". Then I wouldn't have to rely on page ID numbers that could conceivably change. – Eric Aug 27 '13 at 19:56

Not sure if this is exactly what you're looking for, but you may not be aware of the following function: http://codex.wordpress.org/Function_Reference/is_page For example, you could use the following:

if (is_page( 'About' )) {
    // Do Something
| improve this answer | |

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.