Body class in WordPress plays an important role while designing a site. It helps to target a specific page, post or a similar post, page type using WordPress conditional tags.
Most of the time, default output body classes work to customize the elements but sometimes it is important to output a specific class to target those pages or content on a specific page.
Body class is important and can be added on any page including default post and page type using Conditional Tags in WordPress.
1. GLOBAL
Here is the default snippet to output some class globally i.e my-class-name
. Use this in functions.php
add_filter( 'body_class', 'prefix_custom_body_class' ); /** * Adds a css class to the body element. * * @param array $classes the current body classes. * @return array $classes modified classes. */ function prefix_custom_body_class( $classes ) { $classes[] = 'my-class-name'; return $classes; }
2. Conditional
Now, the snippet when we target a page which is a part of Conditional Tags. Use this in functions.php for a specific page name sample-page.
add_filter( 'body_class', 'prefix_custom_body_class' ); /** * Adds a css class to the body element. * * @param array $classes the current body classes. * @return array $classes modified classes. */ function prefix_custom_body_class( $classes ) { //* use conditional tag @https://codex.wordpress.org/Conditional_Tags if ( is_page( 'sample-page' ) ) //* multiple tags → is_singular( array ('post','page') ) $classes[] = 'custom-page-class'; return $classes; }
3. Multiple Condition
We can use array() to target multiple pages with the help of WordPress Conditional Tags. Like we can use this in functions.php
//* Add custom body class to the head add_filter( 'body_class', 'gk_some_body_class' ); function gk_some_body_class( $classes ) { if ( is_singular( array ('post','page') ) ) $classes[] = 'some-class'; return $classes; }
Similarly, One can target archive page using is_archive(), category using is_category() or a CPT archive using is_post_type_archive( ‘portfolio’ ) in functions.php using the above snippet.
Remember: We can include the global snippet in a template to add the custom body class without using a conditional tag as the template itself work as conditional for a specific page.