Lieutenant Dan
Lieutenant Dan

Reputation: 8274

enqueue external plain JS from plugin php to add within footer of theme

I am trying to enqueue an external plain JavaScript file from within my plugin php, to add within my footer of the WP theme. Is this possible?

I've tried the below, but test is failing as no alert is firing...

<?php
/**
Plugin Name: Add Footer JS
*/
add_action( 'wp_footer', 'my_footer_scripts' );
function my_footer_scripts(){
  ?>
  <script>alert( 'Hi Roy' ); </script> // just a test
  <?php
}

So basically; the JS would be at:

http://dev.website.com/wp-content/plugins/mykewlplugin/js/script-support.js

And this PHP, at:

http://dev.website.com/wp-content/plugins/mykewlplugin/support.php

And core plugin PHP/functionality at:

http://dev.website.com/wp-content/plugins/mykewlplugin/mykewlplugin.php

Upvotes: 0

Views: 349

Answers (1)

Xhynk
Xhynk

Reputation: 13870

Make sure that your currently active theme is making use of the wp_footer() and wp_head() functions, as those are required to utilize the appropriate action hooks. With that said, you should really properly enqueue your assets. Anybody else working on the project (including your future self) will be appreciative of that!

This involves utilizing the wp_enqueue_scripts hook and the wp_enqueue_script() function (which relies on both the wp_head() and wp_footer functions).

The proper way to do this would be like the following:

add_action( 'wp_enqueue_scripts', 'no_spex_footer_js' );
function no_spex_footer_js(){
    wp_enqueue_script( 'no-spex-footer-js', '/path/to/your/file.js', array(), null, true );
}

Note all the passed arguments, in order:

  • a unique handle
  • the path to your actual file
  • an array of dependencies by handle (if you rely on jQuery, change this to array('jquery'), etc.
  • version of the file. I use filemtime( plugin_dir_path( __FILE__ ) . 'assets/file-name.js' typically.
  • in_footer - This is the important one, and determines if the file should be loaded into the header or footer.

If you're sure your theme is making use of wp_head() and wp_footer(), and the file isn't working - it means your plugin isn't configured/activated properly, at which point I'd recommend another cursory glance at the Writing A Plugin documentation and the File Header Requirements.

For your specific case, something like this should get you started:

mykewlplugin.php:

<?php
    /**
     * Plugin Name: My Kewl Plugin
     * Description: Does Kewl Things
     * Version:     0.1
     */

    add_action( 'wp_enqueue_scripts', 'my_kewl_plugin_footer_js' );
    function my_kewl_plugin_footer_js(){
        wp_enqueue_script( 'my-kewl-plugin-footer', plugins_url( '/js/script-support.js', __FILE__ ), array(), filemtime( plugin_dir_path( __FILE__ ) . 'js/script-support.js', true );
    }
?>

Upvotes: 2

Related Questions