Add unique CSS classes to BODY tag based on page type

Solved5.31K viewsGeneral
1

This should be added to core plugin, it’s a good practice to have unique body classes for custom pages. Drop this in your functions.php file of your active theme and these classes will show up in <body class=”…”>

// Add specific CSS class to body tag based on Anspress page type
add_filter( 'body_class', 'body_question' );
function body_question( $classes ) {
	if(is_question()){
	$classes[] = 'ap-question-body';
	} elseif(is_ask()){
	$classes[] = 'ap-ask-body';	
	}elseif(is_question_categories()){
	$classes[] = 'ap-categories-body';	
	}elseif(is_question_category()){
	$classes[] = 'ap-category-body';		
	}elseif(is_question_tag()){
	$classes[] = 'ap-tag-body';		
	}elseif(is_ap_user()){
	$classes[] = 'ap-user-body';	
	}
	return $classes;
}

AnsPress Functions 

There may be more, these are the ones I found and needed to use.

  • is_question = true if single question page
  • is_ask = true if page where you ask your question
  • is_question_categories = true if page lists all categories
  • is_question_category = true if single category page
  • is_question_tag() = true if single tag page
  • is_ap_user() = true if single user page (profile)

Setting unique classes for each page type allows you to have some custom CSS specific to those pages, like hiding elements.

1

Is this going to be added to core? Definitely useful!

Already added yesterday.

You are viewing 1 out of 2 answers, click here to view all answers.