WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

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

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

share|improve this question
up vote 1 down vote accepted

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;

share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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