How to add a custom body class to Posts/Pages in WordPress

How-to-add-custom-body-class-to-Posts-Pages-in-WordPress
597 Views
0
(0)

Custom body classes are an excellent way to add distinct designs to various sections of your website. You can target particular sections of your website with CSS styles by adding custom body classes to your WordPress website.

In this guide, we’ll teach you how to add a custom body class to your WordPress Custom Post Type or page.

<?php
add_filter( 'body_class', 'cxc_add_body_classes_call_back' );
function cxc_add_body_classes_call_back( $classes ) {

    // Adds a class if post type is Tools
	if ( is_singular('tools') ) {
		$classes[] = 'tools-single';
	}

    // Add a class if is not Home Page
	if ( ! is_home() ) {
		$classes[] = 'not-home';
	}

    // Add a class if user is Admin
	if ( current_user_can('administrator') ) {
		$classes[] = 'user-is-admin';
	}
	
	return $classes;
}
?>

By following the steps described in this guide, you can quickly add a custom body class to your Custom Post Type and begin styling your website to your specs.

People also read

FAQs

What is a body class in WordPress?

In WordPress, a body class is a CSS class added to the HTML body tag of a web page. Body classes can be used to target specific elements on a web page and apply custom CSS styles.

Why would I want to add a custom body class to my posts/pages?

Adding a custom body class can help you apply custom styles or scripts to specific posts or pages on your WordPress site. For example, you might want to add a unique background image or font to a particular post, or you might want to apply custom JavaScript to a specific page.

How do I add a custom body class to my posts/pages in WordPress?

You can add a custom body class to your posts/pages in WordPress by following the steps given before.

How do I apply custom styles or scripts to my custom body class?

To apply custom styles or scripts to your custom body class, you’ll need to add the relevant CSS or JavaScript code to your WordPress theme or child theme.

How useful was this blog?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this blog.

1 comment

  1. I like the valuable info you supply on your articles. I’ll bookmark your blog and take a look at once more here regularly. I’m rather sure I’ll be told lots of new stuff proper right here! Good luck for the next!

Leave a comment

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