EE Insider Tips
Sponsored by Mijingo's EE 2 Screencasts
ExpressionEngine mini-howtos created by the EE Insider community.
Add a {last_segment} global variable
IMPORTANT UPDATE:
EllisLab has added an official {last_segment} tag as of EE 2.1.1. See info here: http://expressionengine.com/blog/entry/2.1.1_release_what_will_be_there_what_will_not/
—-
Sometimes it is quite handy to pull in the last segment of a URI. EE makes it easy to grab the first segment by using {segment_1} but there is no {last_segment}. With a little help from PHP and path.php we can change that. Add this to your path.php file at the global_vars array*.
<?php
// Get the last segment of the URL and make it a global var
$page_uri = $_SERVER['REQUEST_URI'];
// First we strip the last character of the URL if it is a trailing slash
if(substr($page_uri, -1, 1) == '/')
{
$page_uri = rtrim($page_uri, '/');
}
// now we explode the URI into array segments, then reverse them
$segments = array_reverse(explode('/', $page_uri));
// that makes our new "first" segment our actual last segment (which we make a global var below)
$last_segment = $segments[0];
// Global variables for our site
$global_vars = array(
"last_segment" => $last_segment
);
?>
Now you can use {last_segment} across your site as needed.
* Note that you may need to merge this $global_vars array with your current $global_vars if you’ve already added your own.
Email
Print
Post to Twitter
Erik Reagan — 03:36 on 06.29.2010
It’s also important that this simple approach will use paginated URL segments as well. If you want the {last_segment} global variable to ignore Pagination check out some of these hand add-ons:
http://devot-ee.com/add-ons/last-segment/ (EE 1.x)
http://devot-ee.com/add-ons/bjorn-last-segment/ (EE 2.x)
Wouter Vervloet — 04:56 on 06.30.2010
Hi Erik,
I’ve never tried to use this as a global variable, but doesn’t the following work too?
<?php
global $IN;
// Global variables for our site
$global_vars = array(
"last_segment" => $IN->QSTR
);
?>
EE Documentation on this: http://expressionengine.com/docs/development/usage/input.html#segments
Greetz,
Wouter
Erik Reagan — 05:30 on 06.30.2010
Hi Wouter
Not necessarily. That’s assuming you’re using EE’s designed URL structure of template_group/tempalte_name/query_indicator. Take a look at the parse_qstr() function of system/core/core.input.php and you’ll see how they create that variable.
Out of Control — 06:35 on 07.09.2010
Would it make more sense to use rtrim() instead:
$page_uri = rtrim($page_uri, “/”);
Erik Reagan — 01:37 on 07.12.2010
Great point James. It saves on a function and makes for more efficient code. Thanks