How do I locally enqeue the mediaelement.js file into a wordpress theme

I’m converting a HTML and CSS template into a wordpress theme, When I open the HTMl and CSS file the audio player works normally as it should, but when I convert into a wordpress theme it doesn’t work, I have tried to enqeue the mediaelement-and-player.min.js like this

function music_theme_js() {

    wp_enqueue_script( 'mep_js' , get_template_directory_uri() . '/js/mediaelement-and-player.min.js' , array( 'jquery' ) , '', true);

still nothing shows. Please Help!

It shows up normal when opened through a normal HTML and CSS file

But breaks when I convert to a wordpress theme
Here is the wp_enqueue_script

<?php

function flexing_theme_styles() {

      /* theme's primary style.css file */
  wp_enqueue_style( 'main-css' , get_stylesheet_uri() );


  wp_enqueue_style( 'bootstrap_css' , get_template_directory_uri() . '/css/bootstrap.css' );

  wp_enqueue_style( 'font-awesome_css' , get_template_directory_uri() . '/font-awesome/css/font-awesome.min.css' );

  wp_enqueue_style( 'main_css' , get_template_directory_uri() . '/css/main.css' );



}


add_action( 'wp_enqueue_scripts' , 'flexing_theme_styles' );


function flexing_theme_js() {

    wp_enqueue_script( 'bootstrap_js' , get_template_directory_uri() . '/js/bootstrap.js' , array( 'jquery' ) , '', true);

    wp_enqueue_script( 'jssor.slider_js' , get_template_directory_uri() . '/js/jssor.slider-21.1.6.mini.js' , array( 'jquery' ) , '', true);

    wp_enqueue_script( 'mediaelement_js' , get_template_directory_uri() . '/js/mediaelement-and-player.min.js' , array( 'jquery' ) , '', true);

    wp_enqueue_script( 'main_js' , get_template_directory_uri() . '/js/main.js' , array( 'jquery' ) , '', true);

}


add_action( 'wp_enqueue_scripts' , 'flexing_theme_js' );

?>

1 Answer
1

You need to init the MediaElement.js by doing-

For video or audio tag-

<script>
// using jQuery
$('video,audio').mediaelementplayer(/* Options */);
</script>

And for custom div

<script>
// JavaScript object for later use
var player = new MediaElementPlayer('#player',/* Options */);
// ... more code ...
player.pause();
player.setSrc('mynewfile.mp4');
player.play();
</script>

Just have a look on MediaElement.js wesite.

And it would be better to write the main_js enqueue line like below-

wp_enqueue_script( 'main_js' , get_template_directory_uri() . '/js/main.js' , array( 'mediaelement_js', 'jquery' ) , '', true);

Cause as far as I understood you’ve put you custom JavaScript code in this file. So better enqueue it after MediaElement.js.

And in your HTML file it is working cause I think they have called it in HTML file inside <script></script> tag. And in your theme it is not working cause the init of MediaElement.js is happening before the MediaElement.js is loaded. So better move this code to you custom script file (like main.js) and call it after MediaElement.js.

Hope that helps.

Leave a Comment