Here are 3 methods to add custom classes to the WordPress body
Using PHP Code
With this method, we use the body_class filter to add custom classes to the WordPress body.
1. Open the functions.php file of the active theme.
2. Add the following snippet:
<?php
function custom_body_class( $classes ) {
if ( is_page( 'contatti' ) ) {
$classes[] = 'contatti';
}
return $classes;
}
add_filter( 'body_class', 'custom_body_class' );
- Customize the function according to your needs. In this example, the class “contact” is added to the body of the Contact page.
- Save and close the file.
Using the body_class() Function
With this method, we utilize the body_class function.
1. Open the header.php file of the active theme.
2. Find the line containing the opening body tag and add the desired class within the body_class function. For example, if you want to add the class “homepage” to the homepage, the line should look like this:
<body <?php body_class('homepage'); ?>>
- Save and close the file.
Using a Plugin
- Install and activate the “Custom Body Class“. plugin.
- Go to Settings > Custom Body Class.
- Select the desired options to add classes to the body based on categories, tags, pages, archives, etc.
- Save.
With these 3 methods, you can add custom classes to the WordPress body.
Leave a Reply