0

I have a sidebar displaying in the home and single pages. When it shows up in the home page, it has an already defined css class (width:30%)

When it shows up in the single page, i want to add/insert a new class to that sidebar. I want this new style to modify the predifined elements.So it ends with a width of 35%

I tried to do it as follows:

In functions.php (child theme)

function sidebar_class() {
    if ( is_single() ) {
        $class = 'sidebar-single';
    }
    return $class;
}

In sidebar.php

<div id="secondary" class="sidebar1-area <?php sidebar_class(); ?>" role="complementary">

The html result should be:

<div id="secondary" class="sidebar1-area sidebar-single" role="complementary">

Original css values for the class

width: 30%

Final result

width:35%

How can I accomplish this in the most efficient way?

  • 1
    Well does it not work in the way you did it? Also if your theme uses body_class() properly you could just style .single #secondary – Rarst Sep 12 '13 at 23:18
  • Hi Rarst, it is not working the way I did it. I am using the twentytwelve theme. – Gixty Sep 12 '13 at 23:21
1

How can I accomplish this in the most efficient way?

As Rarst indicates, don't change the class to change the style. Leave the class the same and use CSS Specificity to change the style on certain pages.

When WordPress creates a page in a theme that uses the body_class() function it adds a lot of information about the page in the html class of the body tag. Look at that tag on a page created by single.php and that class will include the class name single.

Use that to specify the style for single.php files.

#secondary {
    /** These styles work on all pages. */
}

body.single #secondary {
    /** These styles only work on single.php pages. */
}

body.home #secondary {
    /** These styles only work on home pages. */
}

See the body_class() function for details on which classes are added.

  • Thats awesome! It worked just the way I wanted. I am still learning my CSS. Thanks to you and Rarst. – Gixty Sep 14 '13 at 18:13
  • By the way, could anyone tell me why the way I was trying to do it didnt work? – Gixty Sep 14 '13 at 18:16
  • You didn't echo sidebar_class() in the PHP call. You just called the function and threw the return value away. – Charles Clarkson Sep 15 '13 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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