0

I have a WordPress plugin, and I must load scripts from my plugin to the front of the site.

class My_Plugin {

function __construct() 
{
    add_action('admin_menu', array(&$this, 'add_submenu'));

    add_action('admin_init', array(&$this, 'admin_init'))

}

function load_my_scripts(){
    wp_enqueue_script('script', 'js/myscript.js');
}

I would like to load my script, so using the right hook which will be able to add the script into all the page of the site.

I've already tried with

add_action('wp_head', array(&$this, 'load_my_scripts'));
add_action('init', array(&$this, 'load_my_scripts'));

etc, ... but I don't find any solution... Could you help me please ?

3

Use wp_enqueue_scripts and admin_enqueue_scripts actions to enqueue your scripts:

// for front end
add_action('wp_enqueue_scripts', array(&$this, 'load_my_scripts'));
// for back end
add_action('admin_enqueue_scripts', array(&$this, 'load_my_scripts'));

Also pay attention that it is bad practice to load your scripts on all pages of the site. Load your script only if need be:

// ...
function load_my_scripts() {
    if ( $some_condition ) {
        wp_enqueue_script('script', 'js/myscript.js');
    }
}
// ...
  • I've also tried this, but I don't understand why my script doesn't load. It works for the admin, not for the front-end. – Zaidar Jun 13 '12 at 13:31
  • does your theme calls wp_footer() function? – Eugene Manuilov Jun 13 '12 at 13:34
  • Oh my gosh, thx a lot, I forget to add my_footer(), but it's was wp_head() which make failing. So I added it and it's work. Thanks a lots !!! – Zaidar Jun 13 '12 at 13:39
1

The most obvious question is to make sure you have the wp_head() tag in your theme header to begin with.

Otherwise straight from the Codex:

 <?php
 function my_scripts_method() {
      wp_enqueue_script(
          'custom-script',
          get_template_directory_uri() . '/js/custom_script.js',
          array('jquery')
      );
 }
 add_action('wp_enqueue_scripts', 'my_scripts_method');
 ?>

Source: http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Load_a_script_from_your_theme_which_depends_upon_a_WordPress_Script

Also double check your paths: http://codex.wordpress.org/Determining_Plugin_and_Content_Directories

  • Thx for the long answer, as you said, it's the wp_head() which wasn't here ! Thx for answer ! – Zaidar Jun 13 '12 at 13:49

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.