I’m creating a plugin that always enqueues a script in the footer. I also have a function that if called would enqueue an additional script that depends on the other one. Here is the basic format of my plugin…
<?php
class MyPlugin {
public function __construct() {
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
}
public function enqueue_scripts() {
wp_enqueue_script('myscript', plugins_url('js/myscript.js', __FILE__), array('jquery'), null, true);
}
public function api() {
add_action('wp_enqueue_scripts', array($this, 'api_scripts'));
}
public function api_scripts() {
wp_enqueue_script('api', plugins_url('js/api.js', __FILE__), array('myscript'), null, true);
}
}
$_GLOBALS['myplugin'] = new MyPlugin();
In my theme’s functions.php file I would like to know when I can make a call to enqueue the script. I’ve tried attaching to plugins_loaded, but the script is not called.
<?php
function myfunction() {
global $myplugin;
$myplugin->api();
}
add_action('plugins_loaded', 'myfunction');
The function
wp_enqueue_scripts
— with an ‘s’– is used as a callback towp_head
. All that the functionwp_enqueue_scripts
does is fire thewp_enqueue_scripts
action. So the last time that you would be able to use the actionwp_enqueue_scripts
is before thewp_enqueue_scripts
callback on thewp_head
hook.In terms of theme templates, that means you need to hook it in before
get_header
, or on a hook that runs early enough in the hook sequence fired as a consequence.Couple of notes:
$GLOBAL
not$_GLOBALS
— inconsistent, I know.plugins_loaded
. That is, just this in the theme’sfunctions.php
:global $myplugin; $myplugin->api();
. I can’t say that I know why the hooked version doesn’t work. I’d guess it is simply too early but would have to do some research to workout the mechanics.after_setup_theme
works and so doeswp_loaded