WordPress.org

Forums

PHP code to know if one is on a page or a post (4 posts)

  1. marcnyc
    Member
    Posted 3 years ago #

    Hello I am looking to find out whether at a given time I am on a page or a post, so that when I am on a page I can apply a different CSS definition.

    Can somebody help me figure out how to do this?

  2. Josh Leuze
    Member
    Posted 3 years ago #

    No problem Marc, depending on your theme, you might not even need to delve into PHP.

    Open up your header.php file, and find the body tag.

    If it looks like this you are good to go:

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

    If your theme has a plain old body tag in it, just replace it with the code above.

    This adds the body_class to your theme, which is an awesome template tag. Just check out the list of classes that it will dynamically add to your body tag.

    You can use those to apply CSS to just pages, just posts, a certain page template, certain blog category, a specific post, your homepage, logged in users, the works!

  3. marcnyc
    Member
    Posted 3 years ago #

    This is a great suggestion!
    Unfortunately the header.php of my theme doesn't have the body class so I had to delve into PHP and used is_page() instead...
    I will let my theme's developer know about this class because it seems very cool.
    Thanks

  4. Josh Leuze
    Member
    Posted 3 years ago #

    What theme are you using Marc? It has to have this bit of code in it to work:

    <body>

    I guess it's possible that it is in a different file than header.php, but it must be in there somewhere.

    If you can find <body>, you should be able to replace it with this to activate the body classes:

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.