1

I am trying to retrieve youtube links from post_content but it does not work..

function get_yts() {
      $query_args = array(
        's' => 'youtube.com/watch?v=',
      );

      $posts = get_posts( $query_args );
      foreach ($posts as $p) {
        $matches = array();
        preg_match('|http://www.youtube.com/watch\?v=([a-zA-Z0-9_]+)|', $p->post_content, $matches);
        echo '$xxmatches: ' . $matches . ' -> '. $p->post_content;
      }
    }

result show be an empty array:

$xxmatches: Array 

what am I doing wrong ?

EDIT:

found better regex which matches really in some editor but not in here:

<?php
        //Enter your code here, enjoy!
$text = '<!-- wp:core-embed/youtube {"url":"https://www.youtube.com/watch?v=ycsODGR5IDQ","type":"video","providerNameSlug":"youtube","className":"wp-embed-aspect-4-3 wp-has-aspect-ratio"} -->
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
https://www.youtube.com/watch?v=ycsODGR5IDQ
</div></figure>';

$matches = array();
preg_match('/http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?‌​=]*)?/', $text, $text);
echo '$xxmatches: ' . sizeof($matches);

shows me 0 size..

  • Are you sure that your search is returning results? What happens when you type $posts = get_posts( $query_args ); var_dump($posts); exit;? youtube.com/watch?v= contains a couple of special characters namely /, ?, & = which could be filtered out or escaped when the search terms are searched for by WordPress. – admcfajn Jan 24 at 15:42
  • you can't echo an array. echo '$xxmatches: ' . implode(', ', $matches) . ' -> '. $p->post_content; – mrben522 Jan 24 at 15:43
  • Also you need to escape special characters in your regex https?:\/\/www\.youtube\.com\/watch\?v=([a-zA-Z0-9_]+) – mrben522 Jan 24 at 15:47
  • This code also won’t match any https YouTube embeds, which I believe is standard these days. – Jacob Peattie Jan 24 at 15:49
  • @jacob just added the s? to that string – mrben522 Jan 24 at 15:50
1

Ok here is working code:

function get_yts() {
  $query_args = array(
    's' => 'youtube.com/watch?v=',
  );

  $posts = get_posts( $query_args );
  foreach ($posts as $p) {
    $input_line = $p->post_content;
    $output_array = array();
    preg_match('/http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?‌​=]*)?/', $input_line, $output_array);
    print_r($output_array);
  }
}

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.