Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 ?

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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');
    }
}
// ...
share|improve this answer
    
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
add comment

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

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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