I'm writing a WP plugin that might be called on any page using a simple function call:getDeck(Deck_id) - and i'd like to add my javascript files on pages where this function is called ONLY, as opposed to having it on every page...

What do I do?


If your scripts can be printed in the footer add the enqueue to the definition of getDeck, with the final argument set to true.

I.e in your plugin file

function getDeck( $deckId )
    wp_enqueue_script( $handle, $src, $deps, $ver, true );

    //do other stuff
| improve this answer | |
  • This one worked better for me, since it's not dependent on the page number, and since it's better to have scripts at the end of the page anyway. – raingod Mar 18 '14 at 17:16

I'm writing a WP plugin that might be called on any page

The issue here is that you want to be able to call the function on any page. And if you're distributing the plugin, you will either require users to add code or you should provide a settings page on which the user can choose on which page the file should load.

If you're developing the plugin for one specific website and you want to add the JS to specific pages, you can do so with is_page():

function my_scripts_method() {
    if( is_page( 'page-name' ) ){
       wp_enqueue_script( /* params */ );

add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); 
| improve this answer | |
  • I believe that I can call my plugin functions on any page anyway, and since i did want to eventually release this, the ther solution - which wasn't page dependent - was better suited for my needs. Thanks for answering, though! – raingod Mar 18 '14 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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