[wp-hackers] Plugins: Best practice for conditional loading of actions and file includes
Otto
otto at ottodestruct.com
Fri Feb 5 20:48:24 UTC 2010
On Fri, Feb 5, 2010 at 2:15 PM, Ade Walker <photofantaisie at gmail.com> wrote:
> On the other hand, all of the hooks used by the plugin are declared in the
> main plugin file - but are not wrapped in any is_admin() conditional checks.
> This results in a situation where, when is_admin() is false, an "admin"
> related hook, eg admin_menu, references a callback function which is defined
> in a file which is not included (thanks to the conditional check mentioned
> above).
It's bad practice to define a hook when you're not defining the
function that the hook points to. So generally, your hook and your
function definition should be located together.
If you're using is_admin to do conditional file includes, then the
hooks should be in those files too. Preferably right above or below
the functions they are hooking, instead of clumped together. This way,
they'll get defined at the same time, eliminating your issue. Also,
somebody looking at the function will know where it gets hooked into,
increasing readability.
So, best practice: Keep hooks near the functions they are hooking. If
you don't like the way that looks, then at least keep them in the same
file.
> Wrapping my hooks in is_admin() checks cures this problem, but it got me
> thinking - why are the errors thrown only by the other plugins?
Plugins that call wp-load directly don't necessarily get the WP_ADMIN
defined, and so is_admin will be false. However, they can still call
anything they like, whether they're in admin or not.
> Or is there something wrong in the way the other plugins are using
> wp-load.php instead of some other method? Or both? :-)
Both, actually. No plugin should *ever* load wp-load directly. It's
never, ever, necessary; it's sloppy programming style; and it's bad
practice. However, it is often quick and easy to understand for some
authors, so it does happen a fair amount. Still, it shouldn't be
there, and any plugin you find with it should be fixed to not require
it any more.
Feel free to pass anybody you find doing this my email, and I'll tell
them how to fix their plugin. :)
-Otto
Sent from Memphis, TN, United States
More information about the wp-hackers
mailing list