WP_LOCALIZE_SCRIPT to pass file path to jscript

I am attempting to develop a youtube embedder plugin. I am doing this as most embedd plugins do not allow to select your own thumbnail for the video.

I ran into issues with my jquery code, where I seem to be unable to define the server path to the thumbnail’s jpeg file (for illustration I kept the jpg file in the same file as the plugin file).

Read More

WHAT AM I DOING WRONG?

Essentially what I am trying to do is to use wp_localize_script to pass on the plugin’s path as a variable (called php_vars) to the youtube-embed.js. Inside there the variable should be used to define the scr attribute of the thumbnail’s img tag. The src attribute will concatenate php_vars + the youtube video IS (v[n].dataset.id) + ‘.jpg”.

HERE THE PHP CODE

function register_youtube_embed_plugin_scripts() 
{
    wp_register_script("youtube-embed-js", plugins_dir_url(__FILE__).'youtube-embed.js', array('jquery'), '', true); // Registers youtube script. I registered the script in the footer for now. 
    wp_enqueue_script("youtube-embed-js");

    $dataToBePassed = array(
    'home'            => plugins_dir_url(__FILE__) .""
    );

    wp_localize_script( 'youtube-embed-js', 'php_vars', $datatoBePassed);
}

add_action("wp_enqueue_scripts", "register_youtube_embed_plugin_scripts");

HERE THE JAVA SCRIPT FILE CALLED youtube-embed.ss

window.addEventListener("load", function(){
    var v = document.getElementsByClassName("youtube-video");
    for (var n = 0; n < v.length; n++) {
        var p = document.createElement("div");
        p.innerHTML = '<img class="youtube-thumb" src="'php_vars.home+ v[n].dataset.id + '.jpg"><div class="play-button"></div>'; // THIS IS THE LINE I AM UNSURE ABOUT.
        p.onclick = youtube_video_clicked;
        v[n].appendChild(p);
    }
}, false);

Any help would will be highly appreciated.

Related posts

1 comment

  1. If you need to define a global js variable that is dynamic to your server route or php script I have found this method to be the safest.

        add_action('wp_head','pluginname_url');
    
    function pluginname_url() {
    ?>
    <script type="text/javascript">
    var home = '<?php echo plugins_dir_url(__FILE__); ?>';
    </script>
    <?php
    }
    

    Add this to your functions.php file in your theme or somewhere in your plugin.
    You js now has access to a variable called “home” which will point to your plugin route url.

Comments are closed.