0

I have a plugin like this:

<?php
/*
Plugin Name: MyPlugin
*/

class MyPlugin
{
  public function __construct()
  {
    add_action('wp_enqueue_scripts', array($this, 'enqueueAssets'));
  }

  public function enqueueAssets()
  {
    wp_register_script('myplugin', plugins_url('myplugin.js', __FILE__), array('jquery'));
    wp_enqueue_script('myplugin');
  }

  // More methods
}

The in a sidebar I create a new instance:

$plugin = new MyPlugin;

But when I open devtools in Chrome and go to "Sources" the assets are not being loaded. If I use a function outside the class it works:

add_action('wp_enqueue_scripts', 'enqueueAssets');
function enqueueAssets()
{
  wp_register_script('myplugin', plugins_url('myplugin.js', __FILE__), array('jquery'));
  wp_enqueue_script('myplugin');
}

class MyPlugin
{

Am I missing something here?

  • I found out that if I instantiate the class inside the plugin it works, but I don't want to do this, I want the class to be instantiated in the sidebar. I could do both but that seems unnecesary... – elclanrs May 11 '13 at 1:59
1

By the time your widget (or sidebar if this is hard-coded) loads you have already missed the wp_enqueue_scripts hook, which runs in the header and that means that you have missed the window for registering the script in the <head> at all, which you are trying to do-- there is no fifth parameter that would load the script in the footer.

You can enqueue in wp_footer or any other hook that runs after wp_enqueue_scripts so long as you add the fifth parameter so that the script loads in the footer.

class MyPlugin
{
  public function __construct()
  {
    add_action('wp_footer', array($this, 'enqueueAssets'));
  }

  public function enqueueAssets()
  {
    wp_register_script('myplugin', plugins_url('myplugin.js', __FILE__), array('jquery'), '', true);
    wp_enqueue_script('myplugin');
  }

  // More methods
} 

While the Codex does state that you should register on wp_enqueue_scripts, it also says:

As of Version 3.3, the function can be called mid-page (before the wp_footer() template tag) or using the wp_head action hook. This will place the script in the footer as if the $in_footer parameter was set to true.

http://codex.wordpress.org/Function_Reference/wp_enqueue_script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.