Search code examples
phpwordpressmedia-library

Creating Dynamic playlist using PHP


I have a playlist script in my wordpress theme that puts the URL from a file in the media gallery into a playlist script that can be read by the audio player.

<script type="text/javascript">
var myPlaylist = [
 <?php
 foreach ($audiofiles as $file)
 {
   echo "{
        mp3:'".$file->guid."',
        title:'".$file->post_title."',
        artist:'"."',
        rating:5,
        buy:'".$file->post_excerpt."',
        price:'"."',
        duration:'"."',
        cover:'"."'
    },"
; }
?>
];
</script>

My problem is that I need to figure out how to change the output of the php script on the LAST item, so that there is no comma after the "}". I've been told this is an AJAX problem, but I'm not sure where to begin.


Solution

  • When passing objects from PHP to JS, the safest, simplest way is to use json_encode. This way you won't have to worry about breaking your JS syntax in case $file->post_title contains ' or any other character that would break it.

    <?php
     $playlist = array();
     foreach ($audiofiles as $file)
     {
       $playlist[] = array(
            'mp3'=>$file->guid,
            'title'=>$file->post_title,
            'artist'=>'',
            'rating'=>5,
            'buy'=>$file->post_excerpt,
            'price'=>'',
            'duration'=>'',
            'cover'=>''
        );
      }
    ?>
    
    <script type="text/javascript">
      var myPlaylist = <?= json_encode($playlist) ?>;
    </script>