WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The code below is the main part of a function in my functions.php which returns a div and script which ultimately output a youtube API iframe to the template where the code had been called from. At the moment it's working fine; however I would like to enqueue the javascript, or at least move it out of my PHP code. I tired moving it to my main JavaScript file ( which is enqueued in the footer ) but it doesn't work when I move it there. Edit: I had hardcoded the vars to avoid having to use wp_localize_script so as to out of the picture.

Surely there's a better way ( or WordPress way ) of doing this?

$return = '

    <div id="' . $postid . 'player"></div>

    <script> var tag = document.createElement("script"); tag.src = "http://www.youtube.com/player_api";
    var firstScriptTag = document.getElementsByTagName("script")[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    var player;
    function onYouTubePlayerAPIReady() {
        player = new YT.Player("'. $postid .'player", {
            height: "315",
            width: "560",
            videoId: "'. $videoID .'",


return $return;
share|improve this question
Main script was already in the footer. Why would I need to check the use of wp_localize_script? – byronyasgur Apr 8 '13 at 20:20
Yes, sorry I know I will have to do that eventually. When I tested moving the script so that it was enqueued I had hardcoded these - will add that to my question. – byronyasgur Apr 8 '13 at 20:26
tried putting it straight into header.php and things went pretty strange, couldn't figure it out – byronyasgur Apr 8 '13 at 22:14
When you say "it doesn't work", it is not really descriptive. What's the expected result and what do you get? Any JS errors in console? – brasofilo Apr 8 '13 at 22:16
Do you mean when I had it in the footer or the header? In the footer it literally produced no output whatsoever that I could detect ( though actually I'm no expert with firebug ) ... in the header I couldn't make head or tail of it at all because it put the iframe in a kind of odd place ( not replacing the div like it should but in a sibling element one level up ) ... anyway what I meant to say was that after 2 hours I was more or less giving up on getting this code enqueued and am going to leave it inline as it works fine, unless someone else wants to have a go. Thanks though. – byronyasgur Apr 8 '13 at 22:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.