WordPress Tutorial - Add page slug to body tag as an ID - Oyova Software
Skip to main content

WordPress Tutorial – Add page slug to body tag as an ID

new php tab

Table of Contents

In this tutorial, I will show you how to add the page name(URL/slug) to the body tag without a plugin. This can be great for targeting specific elements on a page-by-page basis with CSS, jquery, etc. This is a lightweight alternative to using a plugin.

First off, I strongly suggest using sublime text as your text editor. It can be used on both mac and pc. Download it here: https://www.sublimetext.com/.

You will only need to edit two files to accomplish this:

functions.php & header.php

 

I always suggest using child themes. I will create another tutorial on child themes in the future but for now, everything you need to know is here: https://codex.wordpress.org/Child_Themes.

Step 1

Open your functions.php and add the following code:

function body_id() {

    $url = explode('/',$_SERVER['REQUEST_URI']);

    $dir = $url[1] ? $url[1] : 'home';

    echo 'id="' . $dir . '"';

}

 

Adding code to functions.php

Note: If you are working locally and you’re URL is something like http://localhost/mywebsite you will want to change the second line of code to have ‘$url[2]’, such as:

$dir = $url[2] ? $url[2] : 'home';

 

Make sure to change them back to 1s after going live on your main domain.

Step 2

Open your header.php

All we have to do is add this simple line of code to the body tag:

 <?php body_id(); ?>

 

Adding code to header.php

Boom! You’re done!

Step 3

Let’s see it in action.

In the GIF below you can see the body ID changing when I switch between three different pages( services, pricing, and home). It will automatically recognize you are on the home page and add the id of “home”. More complex page names will still work, for example; if your page url is www.mywebsite.com/this-is-a-really-long-page-url your body id will be: “this-is-a-really-long-page-url”.

Chrome Dev Tool Example