Media Playlist Plugin

Here’s a quick example showing how you would pass php data to your script.

First, we hook our function to the wp_enqueue_scripts action. Inside, we enqueue the script that contains the player and initialization code (this is probably two separate files, but I’ve condensed it to a single file in this example). Next, we call wp_localize_script and set some data we want available in our script.

function wpd_test_localize_script() {
    if( is_single() ){
        global $post;
        wp_enqueue_script(
            'test_script',
            get_template_directory_uri() . '/script.js', // or plugins_url() if this is plugin, not theme
            array( 'jquery' ),
            null,
            true
        );
        wp_localize_script(
            'test_script',
            'test_script_data',
            array(
                'title' => $post->post_title,
                'file' => 'hello.mp3'
            )
        );
    }
}
add_action( 'wp_enqueue_scripts', 'wpd_test_localize_script' );

Next, we look at the script.js file we enqueued above, and we can see here how to access the data we passed to it via wp_localize_script:

(function($){
    $(window).load(function(){
        alert( test_script_data.title );
    });
})(jQuery);

test_script_data is the object we created with wp_localize_script. If we load a single post page, the above code will pop an alert dialog with the current post’s title.

If we look in our page source, we can see the script tag WordPress created which contains our data:

<script type="text/javascript">
/* <![CDATA[ */
var test_script_data = {"title":"Some post title","file":"hello.mp3"};
/* ]]> */
</script>

We can pass an array of data as we do above, or we can nest any number of arrays to create multi-dimensional data if necessary (like multiple tracks, each with title, file, etc.).