【问题标题】:How to remove HTML wrapper from YouTube video embeds in Gutenberg on Wordpress如何从 Wordpress 上 Gutenberg 的 YouTube 视频嵌入中删除 HTML 包装器
【发布时间】:2021-03-15 18:08:48
【问题描述】:

简而言之:我使用 Classic Editor 插件创建了一些自定义帖子类型,现在我必须将它们转换为 Gutenberg,但它总是搞砸我的 URL。

CPT 基本上是滑块内的幻灯片,每个都包含一个 YouTube URL 作为帖子内容(或 the_content),它被打印为带有 echo get_the_content 的播放图标元素的 href 属性,它工作正常 - echo get_the_content 的输出是这样的:

https://youtu.be/BFxGJM_sFUg.

但是,在将 CPT 转换为 Gutenberg 块后,get_the_content 的输出为:

<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 -->

由于额外的 HTML,这完全弄乱了布局,所以我的问题是 - 有没有办法阻止 Gutenberg 添加它?我花了几个小时在谷歌上搜索它,找到了一些在正确轨道上的解决方案(尽管它们涵盖的问题不一样),但没有一个对我有用。 :/

谢谢!

【问题讨论】:

  • 如果您找到自己问题的答案,post an answer - 我们也鼓励您这样做。不要编辑问题 - 这个问题仍然只是一个问题。

标签: php wordpress wordpress-gutenberg gutenberg-blocks


【解决方案1】:

由于它是 CPT,因此块标记在转换后应始终以相同的方式包装。使用preg_match 捕获您要查找的URL 字符串,例如:

<?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.
?>

【讨论】:

  • 我认为这是一个很好的答案,但我实际上不希望它们像以前一样被包装,只需要提取 URL,因为我使用 Magnific Popup 显示 YT 视频作为灯箱嵌入并使用我自己的 HTML 标记。或许一开始就应该提到这一点,抱歉。 ://
  • 别担心,很高兴看到你找到了办法。
【解决方案2】:

好的,在此期间我自己想通了。当我将视频显示为嵌入 Magnific Popup 的灯箱时,我只需要从 Gutenberg 块中提取 YouTube URL。所以,解决我的问题的代码是这样的:

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

帖子内容被解析为带有parse_blocks() 的数组,并且通过reset( $blocks[0]['attrs'] 选择['url'],因为它是['attrs'] 数组中的第一项

然后我将get_the_content() 作为函数参数传递并像这样回显函数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-07
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 2019-06-14
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多