Search code examples
phphtmlcssheaderinclude

Highlight current item in the heading php


So I was wondering how do you highlight the current page in the heading of the website. I used the include method to call the heading in all of the pages, but how do I highlight the current page while maintaining the include method in every page.

HEADER.PHP


        <div id="site-content">
            
            <header class="site-header">
                <div class="container">
                    <a href="index.php" id="branding">
                        <img src="images/logo.png" alt="Company Name" class="logo" width="100">
                        <div class="branding-copy">
                            <h1 class="site-title" style="font-size:60px;">Benedicto Law</h1>
                            <small class="site-description">Justice In Words</small>
                        </div>
                    </a>

                    <nav class="main-navigation">
                        <button type="button" class="menu-toggle"><i class="fa fa-bars"></i></button>
                        <ul class="menu">
                            <li class="menu-item"><a href="index.php">Home</a></li>
                            
                            <li class="menu-item"><a href="attorney.php">Attorney</a></li>
                            <li class="menu-item"><a href="service.php">Service</a></li>
                            <li class="menu-item"><a href="contact.php">Contact</a></li>
                        </ul>
                    </nav>
                    <nav class="mobile-navigation"></nav>
                </div>
            </header> <!-- .site-header -->

then I only used <?php include_once('header.php') ?> for calling it to other pages. I wanted it to highlight the current menu item where the user is in. For example: The user pressed Attorney button the Attorney button in the heading should have a highlight. Any help is appreciated thanks


Solution

  • You have at least 2 options.

    1. Pass the data in PHP manually

    Before your include(header statement, create a variable for the onPage and set it. Then use it in your include.

    For example:

    <?php  
    $onPage = 'attorney';
    include_once('header.php') ?>
    

    Then in header.php, check for it like this:

    <li class="menu-item <?php if ($onPage == 'attorney') echo 'active'; ?>"><a href="attorney.php">Attorney</a></li>
    

    2. Automatically detect it

    In header.php

    $onPage = $_SERVER['PHP_SELF'];
    // make sure it's getting just the page, no directory
    $onPage= explode("/",$onPage);
    $onPage = $onPage[count($onPage-1)];
    // remove .php and make sure its lower case
    $onPage = str_replace(".php", "", strtolower($onPage));
    // for /directory/Attorney.php this will give you 'attorney'
    

    The check for it like before

    <li class="menu-item <?php if ($onPage == 'attorney') echo 'active'; ?>"><a href="attorney.php">Attorney</a></li>