Roberto Di Marco

WordPress, WooCommerce Developer.

How to add classes to the WordPress body tag using the body_class function

WordPress

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' );
  1. Customize the function according to your needs. In this example, the class “contact” is added to the body of the Contact page.
  2. 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'); ?>>
  1. Save and close the file.

Using a Plugin

  1. Install and activate the “Custom Body Class“. plugin.
  2. Go to Settings > Custom Body Class.
  3. Select the desired options to add classes to the body based on categories, tags, pages, archives, etc.
  4. Save.

With these 3 methods, you can add custom classes to the WordPress body.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *