You can use the body_class function in your theme’s functions.php file to add custom classes to the body tag of your pages.
function custom_body_classes($classes) {
// Add your custom class
$classes[] = 'my-custom-class';
return $classes;
}
add_filter('body_class', 'custom_body_classes');
After adding this code, every page will have the class ‘my-custom-class’ added to the body tag.
To create custom body classes based on the page title in WordPress, you can use a custom function in your theme’s functions.php file. Here’s an example of how you can achieve this:
function custom_body_classes_by_page_title($classes) {
// Get the current post or page object
$post = get_queried_object();
// Check if the current object is a page or a post
if ($post instanceof WP_Post) {
// Get the title of the page or post
$page_title = $post->post_title;
// Convert the title to a lowercase, hyphen-separated string
$class = sanitize_title_with_dashes(strtolower($page_title));
// Add the custom class to the body classes array
$classes[] = 'page-title-' . $class;
}
return $classes;
}
add_filter('body_class', 'custom_body_classes_by_page_title');
- The get_queried_object() function is used to get the current post or page object.
- We check if the object is an instance of WP_Post to ensure that we have a valid post or page.
- We retrieve the title of the post or page using $post->post_title.
- The sanitize_title_with_dashes function is used to create a hyphen-separated, lowercase version of the title, making it suitable for a CSS class.
- We append the custom class to the body classes array, prefixed with ‘page-title-‘.
- The body_class filter is used to apply these custom classes to the body tag.
After adding this code to your theme’s functions.php file, each page’s body tag will have a class based on its title, making it easy to apply custom styling or target specific pages with CSS. For example, a page titled “Contact Us” will have a body class like page-title-contact-us. Adjust the code as needed to fit your specific requirements.