How can PHP be used to dynamically highlight the current page in a navigation menu using aria-current="page"?
To dynamically highlight the current page in a navigation menu using aria-current="page" in PHP, you can compare the current page URL with the URLs of the navigation menu items. If they match, add the aria-current="page" attribute to the corresponding menu item. This ensures that the screen reader will announce the current page to users.
<?php
// Get the current page URL
$current_page = $_SERVER['REQUEST_URI'];
// Define an array of navigation menu items with their URLs
$menu_items = array(
'Home' => '/',
'About' => '/about',
'Services' => '/services',
'Contact' => '/contact'
);
// Loop through the menu items and add aria-current="page" attribute to the current page
foreach ($menu_items as $label => $url) {
$aria_current = ($url == $current_page) ? 'aria-current="page"' : '';
echo '<a href="' . $url . '" ' . $aria_current . '>' . $label . '</a>';
}
?>
Related Questions
- In the PHP forum thread, users discussed using substr() and strpos() to achieve the desired string truncation. Are there any alternative methods or best practices for achieving the same result?
- How can the order of included files in PHP scripts impact the occurrence of header errors?
- Is it possible to create a continuous video playback feature without user interaction using PHP, and if so, what are the limitations?