0

the condition is:

there's a wordpress site that has 8 categories, and each category has sub-category, and each subcategory has several posts (and still will be updating/counting) :

  • Category A - 8 subcat
  • Category B - 5 subcat
  • Category C - 4 subcat
  • Category D - 3 subcat
  • Category E - 2 subcat
  • Category F - 1 subcat
  • Category G - 5 subcat
  • Category H - 4 subcat

The body_class() function is already exist in header, and I want to make

  • Each category has different background image and custom header (ex: instead of Browsing the "xx" Category text- i'll be using custom words/image)
  • For each single post page belong to certain category, the style is inherit. (i dont know how to explain that on english - but what I want to achieve is: A single post that belong to category A have the same style with Category A archive pages.

I did add:

    .category-A 
    { /* css here */ }

    .category-B
    { /* css here */ }

    etc

but for each single page, the styling did not work..

and to tweak single page that belong to category who- I don't know the code.

So... there's pretty much the rough description of my problem, though. Please help :(

2 Answers 2

1

Category archive pages can be styled using the body class as per your example - WordPress does this out of the box. But for single pages, you need to add this to functions.php:

function add_category_name($classes = '') {
   if(is_single()) {
      $category = get_the_category();
      $classes[] = 'category-'.$category[0]->slug; 
   }
   return $classes;
}
add_filter('body_class','add_category_name');

This will add the body class to the single post, and you can style it with CSS. In order to change the header text, you'll need to use a conditional statement in your archive page template.

if (in_category('this')) { 
    echo 'this';
} elseif (in_category('that')) { 
    echo 'that';
} else { }
1
  • Yes but doesn't work on the home page archive. Dec 30, 2021 at 13:34
0

From what I understand you would like to add a class based on the current category to the <body> of posts and category archives.

There is example code on the body_class codex page which achieve this:

To add a category class to single post pageviews and template files, add the following to the functions.php.

// add category nicenames in body and post class
function category_id_class($classes) {
    global $post;
    foreach((get_the_category($post->ID)) as $category)
        $classes[] = $category->category_nicename;
    return $classes;
}
add_filter('post_class', 'category_id_class');
add_filter('body_class', 'category_id_class');
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.