Search code examples
csswordpressstylesheet

WordPress themes li class active on page


I have just built my first WordPress theme, the only thing I can't seem to work out is how can I tell WordPress to make menu links with the class active when it is on the page? This is the code I had for the static page:

function curPageName() {
  return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);

}

        <?php if(curPageName() == 'index.php'){ ?>
        <li class="current">
            <a href="xxxx" data-description="All starts here">Home</a>
        </li>
        <?php } else{ ?>
        <li>
            <a href="xxxx" data-description="All starts here">Home</a>
        </li>

        <?php } ?>

I have still got this code in the WordPress theme, but it is not working at the moment, I am thinking I could probably make it work as it must have something to do with the exact links, but I'd also like the built the menu in WordPress so that would require me to get rid of this code..

Anyone know what I can do or link me to something that will help me out?


Solution

  • The best way is to assign a page name to the body tag of your page identifying it. Then use php to assign an active class if the page matches.

    CSS

        a.active:hover {
        color:#000;
        border:1px solid #000;
        background:#fff;
        }
    

    HTML

    <body <?php $page = "one" ?>>
    
    <div id="navbar">
        <ul>
            <li><a<?php if($page == 'one'): ?> class="active"<? endif ?> href="one.php">Page 1</a></li>
            <li><a<?php if($page == 'two'): ?> class="active" <? endif ?> href="two.php">Page 2</a></li>
            <li><a<?php if($page == 'three'): ?> class="active" <? endif ?> href="three.php">Page 3</a></li>
            <li><a<?php if($page == 'four'): ?> class="active"<? endif ?> href="four.php">Page 4</a></li>
        </ul>
    </div>
    

    In the above example page one will be active