I am building a gallery in WordPress and I’m trying to grab a specific part of my URL to echo into the id of a div.
This is my URL:
http://www.url.com/gallery/truck-gallery-1
I want to isolate the id of the gallery which will always be a number(in this case its 1). Then I would like to have a way to print it somewhere, maybe in the form of a function.
You should better use
$_SERVER['REQUEST_URI']
. Since it is the last string in your URL, you can use the following function:@Kristian ‘s solution will only return numbers from 0-9, but this function will return the id with any length given, as long as your ID is separated with a
-
sign and the last element.So, when you call
it will echo, in your case,
1
.If the ID will not always be the same number of digits (if you have any ID’s greater than 9) then you’ll need something robust like
preg_match()
or using string functions to trim off everything prior to the last “-” character. I would probably do:Use the $_SERVER[‘REQUEST_URI’] variable to get the path (Note that this is not the same as the host variable, which returns something like http://www.yoursite.com).
Then break that up into a string and return the final character.
Of course you can do other types of string manipulation to get the final character of a string. But this works.