Skip to content

Instantly share code, notes, and snippets.

@earth3300
Last active September 11, 2018 17:59
Show Gist options
  • Select an option

  • Save earth3300/163997be24e699bc4652bd190aba623c to your computer and use it in GitHub Desktop.

Select an option

Save earth3300/163997be24e699bc4652bd190aba623c to your computer and use it in GitHub Desktop.
/**
* Four Ways to Hook into WordPress when using a Class
*
* Do NOT place the action hook in the `_construct`.
*
* @link https://carlalexander.ca/designing-class-wordpress-hooks/
*/
/**
* Call init from outside the class.
*
* But need to pass values to the construct.
*/
class MyPlugin_1
{
public function init()
{
add_action('wp_loaded', array($this, 'on_loaded'));
}
public function on_loaded()
{
// ...
}
}
$my_plugin_1 = new MyPlugin_1();
$my_plugin_1->init();
/**
* Place the action hook outside of the class (decouple). Version I.
*
* This requires *two* actions to get it going.
*/
class MyPlugin_2
{
public static function init()
{
$self = new self();
add_action('wp_loaded', array($self, 'on_loaded'));
}
public function on_loaded()
{
// ...
}
}
add_action('plugins_loaded', array('MyPlugin_2', 'init'));
/**
* Call a class from a static method as a custom constructor.
*
* This method is the briefest, when calling. Requires only one action hook.
*
* Not sure if can pass a value to the construct here if the method is static.
*/
class MyPlugin_3
{
public static function init()
{
$self = new self();
add_action('wp_loaded', array($self, 'on_loaded'));
}
public function on_loaded()
{
// ...
}
}
MyPlugin_3::init();
/**
* Place the action hook outside of the class (decouple). Version II.
*
* No action hook is *inside* the class. This should result in the greatest portability.
*/
class MyPlugin_4
{
public function on_loaded()
{
// ...
}
}
$my_plugin = new MyPlugin_4();
add_action('wp_loaded', array($my_plugin, 'on_loaded'));
/*
* Conclusion: The last two may be the "best".
*
* #3 is the briefest to call.
* #4 places all action hooks outside of WordPress. May be the best if logic only is needed,
* but no direct interaction with WordPress.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment