PHP navigation menu and active page styling

2019-08-12 23:52发布

Hi I'm trying to generate my websites navigation/page buttons and give the active page a style element. What I have at the moment is applying the style element to the home page but when navigating to other pages the style element stays on the 'Home' button rather than applying itself to the current page.

My pages are dynamic with the url being like so: http://www.website.com/?p=contact

<?php

    $current = array(
        "" => "Home",
        "?p=contact" => "Contact Us",
        "?p=about" => "About Us",
        "?p=privacy" => "Privacy Policy"
    );
    foreach( $current as $k => $v ) {
        $active = $_GET['page'] == $k
            ? ' class="current_page_item"'
            : '';
        echo '<li'. $active .'><a href="./'. $k .'">'. $v .'</a></li>';
    }

?>

I've tried a few things but can't seem to get it working correctly, any help would be greatly appreciated. Thank you :)

标签: php html styles
1条回答
Animai°情兽
2楼-- · 2019-08-13 00:12

The following line is the culprit

$_GET['page'] == $k

You should use $_GET['p'] which is your querystring parameter. It will be equal to contact in your example url. So store your array values without the ?p=

<?php

    $current = array(
        "" => "Home",
        "contact" => "Contact Us",
        "about" => "About Us",
        "privacy" => "Privacy Policy"
    );
    foreach( $current as $k => $v ) {
        $active = $_GET['p'] == $k
            ? ' class="current_page_item"'
            : '';
        echo '<li'. $active .'><a href="./'. $k .'">'. $v .'</a></li>';
    }

?>
查看更多
登录 后发表回答