Loading wordpress plugin on specific page only

I am developing a plugin for wordpress that loads javascript in a page.
But i want this plugin to load only on selected pages. Not all pages.
Can someone suggest how to do that?
Here is the code.

add_action('wp_enqueue_scripts', 'soundninja_enqueue');
function soundninja_enqueue($hook)
{
    wp_enqueue_script('soundninja', // id
        'http://soundninja.github.io/SNtest/build/Soundninja.min.js', // path
        array('jquery'), // dependencies
        0, // appends ?ver=$wordpress_version
        true // in_footer
    );
}

Related posts

2 comments

  1. Depending on where you will call your function soundninja_enqueue($hook) you can easily add an if statement asking if the current page/post id is in an allowed list of ids.

    But first you need to get the current page/post id, for this you have a couple of options, depending if are calling the function inside or outside of The loop.

    see here on how to get the current page id in wordpress

    <?php
    $allowedIds = array(12,13,14);
    if (in_array($currentID,$allowedIds)) soundninja_enqueue($hook);
    

    Another option is to pass the the current page/post id as a parameter to the function and do the same if test inside the function, your choice.

Comments are closed.