简体   繁体   English

将活动类添加到菜单项-不是使用wordpress创建的菜单,自定义菜单

[英]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. 有了这个,我得到了有关Page的Main子页面。 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 : 您可以通过使用is_page()来测试用户是否访问了菜单中的活动页面,从而做到这一点:

 <?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='' 您将要在class =“''中使用以下行

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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