WordPress: implementing the body_id() function to assign a different ID to each section of a site

CSS specifications state that an ID selector is more specific than a class selector from the cascading perspective. Nevertheless, WordPress provides only a body_class() function at the moment. We can assign a different ID to each section of a WordPress site by implementing a body_id() function. Let's see the details.

Here's our function:

if(!function_exists('body_id')) {
	
	function body_id() {
		
		global $post;
		global $wp_query;
		$post_id = $post->ID;
		$id = '';
		
		if(is_home() || is_front_page()) {
			
			$id = 'home';
			
		}
		
		if(is_single()) {
			
			$id = 'post-' . $post_id;
			
		}
		
		if(is_page()) {
			
			$id = 'page-' . $post_id;
			
		}
		
		if(is_paged()) {
		
			$current_page = $wp_query->query_vars['paged'];
			
			if($current_page > 0) {
			
				$id = 'paged-' . $current_page;
			
			}
		
		}
		
		if(is_category() || is_archive()) {
			
			$cat_name = get_query_var('category_name');
			
			if(!empty($cat_name)) {
				
				$id = 'category-' . $cat_name;
				
			} else {
				
				$id = 'archive';
				
				
			}
			
			
			
			
		}
		
		
		
		
		if(is_tag()) {
			
			$id = 'tag-' . get_query_var('tag');
			
		}
		
		if(is_404()) {
			
			$id = 'error404';
			
		}
		
		echo ' id="'. $id .'" ';
	}
	
}

An example of how to use this function in your theme:

<body <?php body_id(); ?>>
Back to top