My question is very simple but I haven’t found this answer yet. Here’s an example:
class MyClass {
public function __construct(){
add_action('init', array($this, 'init'));
add_action('wp_footer', array($this, 'footer'));
}
public function init(){
add_action('init', array($this, 'register_scripts'));
}
public function register_scripts(){
wp_register_script('my-script', plugins_url('/script.js', __FILE__));
}
public function footer(){
echo('<div class="style-me">Rawr this is my plugin.</div>');
}
}
This is how my code looks and it’s failing. It displays the div but the javascript does not get applied. So I wondered if my problem was running the init()
function in the init action and then adding register_scripts()
to the init action but I’m already in that action. Is this possible?
3 Answers
You have to use a later (higher) priority. So use current_filter()
to get the current hook and priority, add 1 to that priority, and register the next action:
add_action( 'init', 'func_1' );
function func_1()
{
global $wp_filter;
$hook = current_filter();
add_action( $hook, 'func_2', key( $wp_filter[ $hook ] ) + 1 );
}
function func_2()
{
echo 'hi!';
}