GetSimple Support Forum

Full Version: Execute Hooks on pages without Hooks.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This might come in handy for someone...

When writing my latest plugin I need a hook on the pages.php page, unfortunaltely there is only header and footer executed on that page. Hooking into "footer" meant my function were run on all backend pages.

This little snippet allows you only to run on the pages you want;

Code:
$bt = debug_backtrace();
$shift=count($bt) -1;    

if (pathinfo_filename($bt[$shift]['file'])=="pages"){     // changes pages to the page your looking for.
    add_action('footer','your_function',array());    
}
Nice tip Mike.
I've also been experimenting with this... What do you think of this other way?
Code:
$sn=$_SERVER["SCRIPT_NAME"];
if (substr($sn,strrpos($sn,"/")+1)=="pages.php") {
    // ...
}
(checking the file with suffix -- 'pages.php' instead of 'pages')
8)

Yes certainly a lot easier....
Carlos Wrote:
Code:
$sn=$_SERVER["SCRIPT_NAME"];
if (substr($sn,strrpos($sn,"/")+1)=="pages.php") {
    // ...
}
(checking the file with suffix -- 'pages.php' instead of 'pages')
You could probably get the suffix out as well (untested):
Code:
$sn=$_SERVER["SCRIPT_NAME"];
if (substr($sn,strrpos($sn,"/")+1,-4)=="pages") {
    // ...
}
Just for the sake of making it even easier and shorter.
Zegnåt Wrote:Just for the sake of making it even easier and shorter.

:-D
Yeah, 2 chars shorter, but I find it more readable (understandable) with ".php"
More on this...
What do you think would be better?

Code:
if (...) {
    add_action('footer','your_function');
}

function your_function() {
  // code...
}

Or this:

Code:
add_action('footer','your_function');

function your_function() {
  if (...) {
    // code...
  }
}

First is like Mike's tip. In the second one the check for the current page is done inside the hooked function.
I think 1st option is better as its wont have to register the call to the hook, which will get executed.

Less calls to the hooks the better..