Removing page, post, tag, category, and taxonomy IDs from the body_class in WordPress

WordPress loves to add a wide range of CSS classes to the body of a page, depending on what type of page it is, what resources it uses, and so on. Some of this is helpful (like ‘archive’, ‘post’ and the page format classes – ‘single-format-gallery’, ‘single-format-image’ etc.), but some of the tags are just noise – like the tags that have the post/page/category/tag/term IDs. There are a couple of ways to remove tags that you don’t want by filtering the body_class function. You can remove all generated classes, or add new ones, but selectively removing classes is a bit more tricky, depending on what you want to remove.

This function will strip out the IDs WordPress adds to tags, categories, pages, posts and taxonomy pages.

add_filter('body_class','remove_ID_classes_from_body', 50 );
function remove_ID_classes_from_body( $classes ) {
	global $wp_query;
	$page_query = $wp_query->get_queried_object();

	if(is_tag() || is_tax() || is_category()) {	
		$classes = array_diff( $classes, [( is_tag() ? 'tag-' : ( is_tax() ? 'term-':'category-') ) . $page_query->term_id] );
	} elseif (is_single() || is_page() ) {
		$classes = array_diff( $classes, [( is_page() ? 'page-id-' :'postid-').$page_query->ID] );
	}
	return array_unique( $classes );
}

Variable names in WordPress (or why you should never use $category as a variable name)

The great thing about WordPress and PHP is that you can call variables anything you like. The bad thing about WordPress and PHP is that you can call variables anything you like…

Think about these variables:

$post, $category, $template

What do they have in common? Well, they all look like good, descriptive variable names don’t they? What if you changed this to

global $post, $category, $template;

and then put this in a template for a post…?

echo $post; echo $category; echo $template;

Well, you’d get all sorts of interesting things, as $post, $category and $template are all global variables in WordPress.

FYI: there is a (partial) list of WordPress global variables in the Codex.

So if you use these variable names, and you also access global variables with those names… sometimes you’ll be thinking: why doesn’t my code work? And you’ll find out that when you thought you were changing a local variable you were actually changing a global variable, and that affected something else…

See also: Global variables and understanding scope in WordPress.