0

I want function that scan wordpress posts for youtube links or youtube shortcode and when found it, with regex selects only code from url (like '2SaZO4Gmfdc') and echo that code.

For now, i edited one plugin that do exacly same this, but instead of echoing code, it echoes something like img.youtube.com/vi/2SaZO4Gmfdc/0.jpg

So, for now, i have this code http://pastebin.com/6M70xpTX and it's not working, and plugins code that works is here pastebin.com/MX2fca96

1

Hi @Саша Стефано:

Maybe I'm missing something but at first glance it looks like you just need to add a return statement (I've not tested this code so if that's not it let me know and I'll dig in to figure it out):

function get_youtube_kod($post_id=null) {
  // Get the post ID if none is provided
  if($post_id==null OR $post_id=='') $post_id = get_the_ID();

    // Gets the post's content
    $post_array = get_post($post_id); 
    $markup = $post_array->post_content;

    // Checks for a standard YouTube embed
    preg_match('#<object[^>]+>.+?http://www.youtube.com/v/([A-Za-z0-9\-_]+).+?</object>#s', $markup, $matches);

    // Checks for any YouTube URL
    if(!isset($matches[1])) {
      preg_match('#http://w?w?w?.?youtube.com/watch\?v=([A-Za-z0-9\-_]+)#s', $markup, $matches);
    }

    // If no standard YouTube embed is found, checks for one embedded with JR_embed
    if(!isset($matches[1])) {
      preg_match('#\[yt url=([A-Za-z0-9\-_]+)]#s', $markup, $matches);
    }

    if(!isset($matches[1])) {
      preg_match('#\[yt url=([A-Za-z0-9\-_]+)[^>]*]#s', $markup, $matches);
    }

    // If we've found a YouTube video ID, create the thumbnail URL
    if(isset($matches[1])) {
      $youtube_kod = $matches[1];  
    }
    return $youtube_kod;

};
  • Not working Mike, don't know why, just tested it. I'm calling this code with both <?php echo $get_youtube_kod; ?> and <?php $get_youtube_kod; ?> and not working at all ... – Саша Стефановић Jan 28 '11 at 11:49
  • @Саша Стефановић - You are calling as <?php $get_youtube_kod; ?> and not as <?php get_youtube_kod($post->ID); ?>? (Also, can I assume you calling in The Loop?) – MikeSchinkel Jan 28 '11 at 12:22
  • Yes Mike, i did this with different function. Thanks, i marker your answer as "yes". – Саша Стефановић Jan 28 '11 at 14:57
  • @Саша Стефановић - Glad I could help. – MikeSchinkel Jan 28 '11 at 18:22

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.