简体   繁体   中英

Add active class to the menu item - not menu created with wordpress, custom menu

I have a menu created with this code

                   <?php
                      $pages = get_pages('child_of= 8&sort_column=post_date&sort_order=asc&parent=8');
                      foreach($pages as $page) {  
                    ?>
                     <li><a href="<?php $permalink = get_permalink($page->ID);
                        echo $permalink ; ?>"><?php echo $page->post_title ?></a></li>
                    <?php } ?>

With this I got the Child Pages of Main about Page. And I need to add active class in this items depending on which page i am(menu created with code above).

You can do that simply by use is_page() to test if the user visit the active page in your menu :

 <?php
 $pages = get_pages('child_of= 8&sort_column=post_date&sort_order=asc&parent=8');

 foreach ( $pages as $page ) {
    if ( is_page( $page->ID ) ) {
        $active = 'class="active"';
    } else {
        $active = '';
    }
    echo '<li '.$active.'><a href="'.get_permalink($page->ID).'">'.$page->post_title.'</a></li>';
 }
 ?>

You will want to use the following line inside class=''

If(get_the_ID()==$page->ID) echo 'class="active"';

将此添加到您的<li> (或您希望的<a> )标记中:

<?php if ( get_the_ID() == $page->ID ) echo ' class="active"'; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM