• Resolved virgild

    (@virgild)


    I tried a bunch of examples and nothing seems to work. I simply want to load a js in my blog. (but not in admin pages)

    This is the code I added to the bottom of my plugin php file

    function load_js_file()
    {
    	wp_enqueue_script('jquery');
    	wp_enqueue_script('the_js', WP_PLUGIN_URL.'/my_plugin/my_javascript.js');
            echo "test";
    }
    
    add_action('wp_head', 'load_js_file');

    It echoes the “test” but no script is loaded. I’m not sure what I’m doing wrong.. Everything else works.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Update your enqueue line to read..

    wp_enqueue_script('the_js', plugins_url('/my_javascript.js',__FILE__) );

    NOTE: Even when an enqueue points to an invalid path it still gets output into the source of the page, if you don’t see the script working, check the source and verify the javascript file’s include path is correct.

    Thread Starter virgild

    (@virgild)

    Thanks Mark!! That works! I noticed that the script is also loading in wp-admin pages. Is there a way to load it just on the blog like index, single post, etc?

    You could put some conditional tags around the enqueue.

    Thread Starter virgild

    (@virgild)

    Thanks

    @virgild

    function my_init() {
      if (!is_admin()) {
        wp_enqueue_script('the_js', plugins_url('/my_javascript.js',__FILE__) );
      }
    }
    add_action('init', 'my_init');

    This works for me to keep the script on the front end.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Adding js file via plugin using wp_head action (doesn't work)’ is closed to new replies.