phynam
phynam

Reputation: 465

Change CSS on nav menu parents and children

I have a PHP script that will assign CSS attributes to headings based on which menu item they appear under.

I have this menu structure. About and its children need to have orange headings and Services and its children need to have purple headings

ABOUT SERVICES page1 page 4 page2 page 5 page3 page 6

Currently my scripts will detect whether a page is a child of a certain page but all of the headings are styled with that of the first if statement of my script. (i.e. I check for services first and everything is assigned a purple heading)

Here are the two scripts, could anyone tell me what is going wrong?

if(get_the_title($ID) === "Services" || is_tree($ID) == true) {
     echo '<style type="text/css">
                .header-page h1 {
                        background-color: #9B87A9;
                    }

                    .header-page h2 {
                        background-color: #9B87A9;
                    }
                </style>';
}

else if(get_the_title($ID) === "About" || is_tree($ID) == true) {
    echo '<style type="text/css">
                .header-page h1 {
                        background-color: #dea949;
                    }

                    .header-page h2 {
                        background-color: #dea949;
                    }
                </style>';
}

and the second script/function:

function is_tree($pid) {      // $pid = The ID of the page we're looking for pages underneath
global $post;         // load details about this page
if(is_page()&&($post->post_parent==$pid||is_page($pid))) 
           return true;   // we're at the page or at a sub page
else 
           return false;  // we're elsewhere
};

Upvotes: 0

Views: 78

Answers (1)

alou
alou

Reputation: 1502

You should not echo some CSS inside style tags, but rather conditionally assign classes to your menus or menu items and then use css for the specific classes.

What you are doing here is assigning the same styles to all .header-page h1 elements (is that the menu title?), which will apply to all <h1 class="header-p[age"> .

If your ABOUT menu had a distinct class, let's say .about you would just use different css for this element, without needing to use php conditionals.

Example, with html and css:

<h1 class="header-page about">About</h1>
<ul class="menu about">
 ...
</ul>


 <h1 class="header-page services">Services</h1>
 <ul class="menu services">
 ...
 </ul>

And now you can apply styles without the conditional:

 <style>
 h1.header-page.about {color:black}
 ul.menu.about {color:red}
 h1.header-page.services {color:green}
 ul.services {color:yellow}
 </style>

Upvotes: 1

Related Questions