Detecting page file name using php?

I am making a menu on a Wordpress template and need a menu to locate the current page and select it. So, for example, my menu:

<li><a href="index.php" class="current">Home</a></li> <li><a href="about.php">About</a></li> 

So, if the user is on the About page, I want him to have "class = current". How is this possible? I hear that using $_SERVER['PHP_SELF'] possible? Please rate that I have zero knowledge in php coding, so kindly do all the answers in detail.

+4
source share
3 answers

I use a small snippet like this. If your visitor is on about.php , $basename will be about .

 $basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4); 

HTML There will be something like this.

 <li><a href="index.php"<?php if ($basename == 'index') echo ' class="current"'; ?>>Home</a></li> <li><a href="about.php"<?php if ($basename == 'about') echo ' class="current"'; ?>>About</a></li> 
+11
source
 $myPage = $_SERVER['PHP_SELF']; <li><a href="index.php" class="<?echo ($myPage == 'index.php'?'current':'')?>">Home</a></li> <li><a href="about.php" class="<?echo ($myPage == 'about.php'?'current':'')?>">About</a></li> 
+1
source

You can use something from the form:

 <li><a href="index.php"<?php if($_SERVER['PHP_SELF'] == 'index.php') echo ' class="current"'); ?>>Home</a></li> <li><a href="about.php"<?php if($_SERVER['PHP_SELF'] == 'about.php') echo ' class="current"'); ?>>About</a></li> 

However, you probably want to include the above in a function.

Regardless, I would recommend reading the PHP manual at the beginning of the section before going any further - this will be a reasonable time.

0
source

Source: https://habr.com/ru/post/1335285/


All Articles