WP REST – video and audio players

I’m building a VUE JS based theme, and I’m using WP REST v2.
There is a problem – I can’t make video and audio playlists work (built-in WP core feature). I already added:

wp_enqueue_style( 'wp-mediaelement' );
wp_enqueue_script( 'wp-playlist' );

but from there I’m not sure how to make it work.

I just can’t make it work. When I insert content from the REST API into DOM the video and and music playlists are not working.

I have access to WPPlaylistView so I also tried:

jQuery(".wp-playlist:not(:has(.mejs-container))").each(function() { return new WPPlaylistView({ el: this }); });

But I’m still getting the error : “Uncaught TypeError: Cannot read property ‘replace’ of undefined

Does somebody know how to deal with this problem?
How can I make these WordPress playlists work when the player code is added to the DOM after the page loads?

1 Answer
1

Ran into this same issue and I found the answer after many hours and almost giving up. It’s in a bit of code that written to make the Customizer work with playlists. Checkout this comment from /wp-includes/widgets/class-wp-widget-text.php:

    /**
     * Enqueue preview scripts.
     *
     * These scripts normally are enqueued just-in-time when a playlist shortcode is used.
     * However, in the customizer, a playlist shortcode may be used in a text widget and
     * dynamically added via selective refresh, so it is important to unconditionally enqueue them.
     *
     * @since 4.9.3
     */
    public function enqueue_preview_scripts() {
        require_once dirname( __DIR__ ) . '/media.php';

        wp_playlist_scripts( 'audio' );
        wp_playlist_scripts( 'video' );
    }

So this is being used in the customizer, which also loads the HTML dynamically after the page has loaded. If we want to do a similar thing on the front end, we will also need to definitely load these things when the page first loads. Here’s the code I ended up using:

function squarecandy_wp_enqueue_scripts() {
    wp_enqueue_script( 'wp-playlist' );
    require_once get_home_path() . 'wp-includes/media.php';
    wp_playlist_scripts( 'audio' );
    wp_playlist_scripts( 'video' );
}
add_action( 'wp_enqueue_scripts', 'squarecandy_wp_enqueue_scripts' );

Boom! Now you can run wp.playlist.initialize() in your js at anytime without errors.

One more thing to note: This issue can be particularly vexing to troubleshoot because if you have a page that naturally contains a playlist on the initial page load, then you can load additional playlist HTML on to the page and then run wp.playlist.initialize() and everything works out fine. It only fails if you have no playlists on your initial page (so this mysterious “just-in-time” enqueue never happens) and then you try and load in a playlist later.

Leave a Comment