• I’m attempting to conditionally include a javascript file that is located in my plugin directory. I’ve read several posts on the proper way to include JS in the WP Admin, including: 5 tips for using ajax in wordpress, codex entry for wp_enqueue script, and Justin Tadlock’s post on loading Javascript from DevPress, as well as the entire chapter on AJAX in the WROX WordPress Plugin development ebook.

    The JS file I’m attempting to include is: (path from root)
    /wp-content/plugins/my-plugin/script.js

    so, in my plugin’s main php file, I registered the js:

    function tacca_register_scripts() {
    	wp_register_script( 'tacca_content_ajax', plugins_url( '/script.js', __FILE__ ), array( 'jQuery' ) );
    
    }
    add_action( 'admin_init', 'tacca_register_scripts' );

    and then I create a function to actually try and print the script in the head, only on the post editor page (/wp-admin/post.php):

    function tacca_javascript_eq( $hook ) {
    
    	wp_enqueue_script( 'tacca_content_ajax' );
    
    }
    add_action( 'admin_head-post.php', 'tacca_javascript_eq' );

    This fails to print in head. It also fails when I attach the function to the admin_print_scripts,admin_head,admin_enqueue_scripts

    However, if I inline a javascript like, this:

    function tacca_javascript_eq() {
    ?>
    	<script>alert('Hello, I loaded just fine');</script>
    <?php
    }
    add_action( 'admin_head-post.php', 'tacca_javascript_eq' );

    it successfully prints the javascript.

    Am I doing something glaringly obvious wrong, here?

    Thanks in advance for you help!

    – Greg J

Viewing 2 replies - 1 through 2 (of 2 total)
  • You can call wp_enqueue_script right after wp_register_script. So your code would look like:

    function tacca_register_scripts() {
    	wp_register_script( 'tacca_content_ajax', plugins_url( '/script.js', __FILE__ ), array( 'jQuery' ) );
    	wp_enqueue_script( 'tacca_content_ajax' );
    }
    add_action( 'admin_init', 'tacca_register_scripts' );

    or instead of the ‘admin_init’ action, you could also use ‘admin_enqueue_scripts’ :

    http://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts

    Yes, it sounds like you’re calling wp_enqueue_script() too late to be included in the header. An inline script would work because there’s no queue; it’s just direct output. I’d try ‘admin_init’ like jason_lane suggested or maybe set the flag to include your script in the footer instead of the header.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘help! wp_enqueue_script is including my javascript.’ is closed to new replies.