Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Execute Hooks on pages without Hooks.
#1
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());    
}
My Github Repos: Github
Website: DigiMute
Reply
#2
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')
Reply
#3
8)

Yes certainly a lot easier....
My Github Repos: Github
Website: DigiMute
Reply
#4
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.
“Don’t forget the important ˚ (not °) on the a,” says the Unicode lover.
Help us test a key change for the core! ¶ Problems with GetSimple? Be sure to enable debug mode!
Reply
#5
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"
Reply
#6
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.
Reply
#7
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..
My Github Repos: Github
Website: DigiMute
Reply




Users browsing this thread: 3 Guest(s)