Вопрос

I have a function in my functions.php file which takes any embedded YouTube URL, appends &rel=0 to the end of the URL, and wraps it in a <div>. It works perfectly for YouTube URLs I paste into any page or post:

function embed_youtube_parameters( $code ) {
    if( strpos( $code, 'youtu.be' ) !== false || strpos( $code, 'youtube.com' ) !== false || strpos( $code, 'youtube-nocookie.com' ) !== false ) {
        $return = preg_replace( '@embed/([^"&]*)@', 'embed/$1&rel=0', $code );
    }
    return '<div class="video-container">' . $return . '</div>';
}
add_filter( 'embed_oembed_html', 'embed_youtube_parameters' );

I also have a custom post type (added via a plugin I use), which has a filter that I can use to customise the output of the single custom post type pages it generates. So I have that filter also in my functions.php file.

It's quite a long filter, but part of it looks like this:

<?php if ( get_cpt_meta( 'cpt_video_link' ) ) : ?>
<div class="cpt-video">
    <?php echo wp_oembed_get( get_cpt_meta( 'cpt_video_link' ) ); ?>
</div>
<?php endif; ?>

The custom post type uses a bunch of custom fields, one of which is for a YouTube URL (cpt_video_link). So the part of the filter I've shown above should echo the YouTube URL using wp_oembed_get, which - as far as I understand it - should work the same as pasting a YouTube URL onto a regular page or post - in the sense that it's using oEmbed.

My assumption is that - because it's using oEmbed - it should therefore also work with my embed_youtube_parameters function (above), meaning that it should have &rel=0 appended to the end of the URL, and wrapped in the <div class="video-container">.

However this is not the case, and I can't figure out why. My goal is for the embed_youtube_parameters function to be applied to my CPT filter. Can anyone give me some pointers as to why this isn't happening?

Это было полезно?

Решение

After looking at the code reference for wp_oembed_get (and WP_oEmbed::get_html()) I don't think embed_oembed_html fitler gets fired when that function is called. But I might have missed something.

You could try using WP_Embed::shortcode( array $attr, string $url = '' ) instead of wp_oembed_get as this would mimic what happens with the native post types and the filter would get fired, I think.

Something like this. Updated 23.12.19

<?php if ( get_cpt_meta( 'cpt_video_link' ) ) : ?>
  <div class="cpt-video">
    <?php
      $embed = new WP_Embed();
      echo $embed->shortcode(array(), get_cpt_meta( 'cpt_video_link' ));
    ?>
  </div>
<?php endif; ?>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с wordpress.stackexchange
scroll top