I’m using WAMP and the root folder of my page is: http://localhost/projects/bp/
In a Worpress application and I want to give unique id’s to the body tag of every Page. So I did the following:
<?php
$page = $_SERVER['REQUEST_URI'];
$page = str_replace("/","",$page);
$page = str_replace(".php","",$page);
$page = str_replace("?s=","",$page);
$page = $page ? $page : 'default'
?>
<body id="<?php echo $page ?>">
When I clicked the Aboutpage the URL change to the following: http://localhost/projects/bp/about and $page showed the following value:projectsbpabout
What can I do so that $page just show the last word of the URL. In this case, about, I don’t want the projectsbp part)?
Do I have to change something in the WordPress routing?
I would use PHP’s built-in path parsing functions to do this.
Use parse_url() to cut off the query and get only the path part:
(parse_url is used to parse full URLs but should work fine for this. The second parameter is available since PHP 5.1.2.)
Then use basename() to extract the file name:
Additional thougths
Depending on how your site is structured, this method will not necessarily make for unique IDs. What if
aboutis a sub-page in/bpand/bc? (If that is possible in WordPress.) You would have two different pages with the same ID. In that case, you may want to use the full path as an identifier, converting slashes into underlines:also from own experience, I recommend using classes for this to avoid ID collisions if a page is named like an already existing elements on the page!