How to remove HTML wrapper from YouTube video embeds in Gutenberg on Wordpress

1k Views Asked by At

in short: I had some custom post types created with the Classic Editor plugin and now I have to convert them to Gutenberg, but it keeps screwing up my URLs.

The CPTs are basically slides inside a slider, and each one of them contained a YouTube URL as the post content (or the_content), which was printed as the href attribute of the play icon element with echo get_the_content and it worked fine - the output of echo get_the_content was this:

https://youtu.be/BFxGJM_sFUg.

However, upon converting the CPT to Gutenberg blocks, the output of get_the_content is:

<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
https://youtu.be/BFxGJM_sFUg
</div></figure>
<!-- /wp:core-embed/youtube -->

which completely messes up the layout because of the extra HTML, so my question is - is there any way to prevent Gutenberg from adding it? I've spent hours Googleing it, found some solution that were kinda on the right track (although the issue they cover wasn't the same), but none of them worked for me. :/

Thanks!

2

There are 2 best solutions below

2
On

As it's a CPT, the block markup should always be wrapped the same after conversion. Use preg_match to capture the URL string you are looking for, eg:

<?php
        // Start the Loop.
        while ( have_posts() ) :
            the_post();

            $block_content = get_the_content();
            // Find the youtube url inside <div>...</div>
            preg_match('/<div[^>]*>(.*?)<\/div>/s', $block_content, $match);
    
            echo $match[1]; // contains "https://youtu.be/BFxGJM_sFUg" 

        endwhile; // End the loop.
?>
0
On

Okay, figured it out on my own in the meantime. I needed to extract only the YouTube URL from the Gutenberg block as I was displaying videos as lightbox embeds with Magnific Popup. So, the code that solved my problems was this:

function extract_block_url( $content ) {
  $blocks = parse_blocks( $content );
  $blocks = reset( $blocks[0]['attrs'] );
  return $blocks;
}

The post content is parsed into an array with parse_blocks() and the ['url'] is selected via reset( $blocks[0]['attrs'] as it's the first item in the ['attrs'] array

Then I pass get_the_content() as the function argument and echo out the function like this:

<a href="<?php echo extract_block_url( get_the_content() ); ?>" class="play-icon">