A common method to target elements of a particular static Page is by its ID like this: .page-id-2
Wouldn’t it be handy if you could instead use the slug of the Page like this? .page-about
Adding the following in child theme’s functions.php will automatically add a page-slug class to the body element for all static Pages for easier targeting in CSS.
add_filter( 'body_class', 'sk_body_class_for_pages' ); | |
/** | |
* Adds a css class to the body element | |
* | |
* @param array $classes the current body classes | |
* @return array $classes modified classes | |
*/ | |
function sk_body_class_for_pages( $classes ) { | |
if ( is_singular( 'page' ) ) { | |
global $post; | |
$classes[] = 'page-' . $post->post_name; | |
} | |
return $classes; | |
} |
What a brilliant idea! Thanks, Sridhar :).
Thank you! You pushed me to the right way.
Thank you! 🙂
Thanks a lot.
Exactly what I was looking for.
Thanks, Buddy. You saved my ass! 😀
I know it’s been a while since this blog was posted but I thought I would share an easier way with your viewers. There is a WordPress plugin called “WP247 Body Classes” that will allow you to add a myriad of admin selectable classes to the HTML body tag based on all kinds of conditions. You can set classes based on the mobile device used to browse the site. You can set classes based on user roles and capabilities. You can set classes based on the Archive being viewed or the page/post being viewed. You can also add body classes to individual pages/posts (like desired here). Then you can use those body classes to style your pages as you see fit. All of this can be done without requiring any custom code. As an example, to solve the problem presented in this post, you would simply install and activate the “WP247 Body Classes” plugin, go to Settings->Body Classes, select the “Post Classes” tab and check the box next to “is-page-(slug)”, and save your settings. You pages will now contain an HTML body tag class called “is-page-?” where “?” is the page slug. Now you can style your about page using “body.is-page-about { … }” CSS styling.
You may want to set up SSL on your site.