I'm trying to load a YouTube video via ajax outside the loop. I have it working on regular pages, but not anything loaded via ajax. A user would click a button, then a YouTube video will load via ajax, and auto-play.

The AJAX portion is working correctly. It loads my video.php file, but then when it attempts to grab the YouTube link from the post meta, it dies.

Here's my video.php file...

global $post;
$g_id = $post->ID;
$p_type = get_post_type( $g_id ).'_post_class';
$meta = get_post_meta( $g_id, $p_type, true );
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $meta, $match);
$dynamicstring = $match[0];
$newstring = substr($dynamicstring, -11); //grab the last 11 characters

<iframe src="<?php echo '//www.youtube.com/embed/' .$newstring. '?autoplay=1'; ?>" frameborder="0" allowfullscreen></iframe>

So i'm trying to grab the post ID and it's type, then get the meta data, then preg_match for the last 11 characters, and store them in a variable called $newstring. Then I use this:

echo 'www.youtube.com/embed'. $newstring;

$newstring spits out blank because when I load the file via Ajax, something is missing and I don't know where to start.

A pointer would be appreciated! Please & Thank You.

EDIT: Put my global variable attempts in. Still getting this error on get_post_type() and get_post_meta().

Call to undefined function

  • I believe you need to pass post ID when calling ajax to get $g_id. – Nilambar Sharma Sep 22 '14 at 3:06
  • I've tried passing it with global $wp_query, but i'm still getting an error during get_post_meta. Hmm. – The_Other_J Sep 22 '14 at 18:46
  • 1
    2 things - you have to pass the post ID with your AJAX request, there is no $post or $wp_query in the context of your php code, it's an entirely separate request from the one that you're making the AJAX request from. You should also look at the codex page for AJAX in Plugins to learn how to use AJAX in WordPress, you can't call a php file directly and use the WordPress API, since your video.php is loaded outside the context of WordPress environment. – Milo Sep 22 '14 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.