WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Adding js file via plugin using wp_head action (doesn't work) (6 posts)

  1. virgild
    Member
    Posted 3 years ago #

    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.

  2. Mark / t31os
    Moderator
    Posted 3 years ago #

    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.

  3. virgild
    Member
    Posted 3 years ago #

    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?

  4. Mark / t31os
    Moderator
    Posted 3 years ago #

    You could put some conditional tags around the enqueue.

  5. virgild
    Member
    Posted 3 years ago #

    Thanks

  6. Brayne
    Member
    Posted 3 years ago #

    @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.

Topic Closed

This topic has been closed to new replies.

About this Topic