WordPress主题开发:如何调用Gutenberg视频/嵌入/HTML区块视频
Hey there! I totally get the confusion with Gutenberg when you're new to WordPress theme development—those blocks can feel like a maze at first. Let's fix your code so it properly pulls in the video, YouTube embed, and HTML blocks your admins are adding.
Instead of just checking if the blocks exist, you need to extract and render those specific blocks without outputting the entire post content. Here's how to replace that **show video here** section:
<?php // Parse the post content into individual Gutenberg blocks $post_blocks = parse_blocks( get_the_content() ); // Loop through each block to find our target types foreach ( $post_blocks as $block ) { // Define the block types we want to display $target_blocks = [ 'video', 'core-embed/youtube', 'html' ]; // Check if the current block is one of our targets if ( in_array( $block['blockName'], $target_blocks ) ) { // Optional: Filter HTML blocks to only keep those with video content if ( $block['blockName'] === 'html' ) { // Skip HTML blocks that don't have video or iframe tags if ( strpos( $block['innerHTML'], '<video' ) === false && strpos( $block['innerHTML'], '<iframe' ) === false ) { continue; } } // Render and output the block (preserves Gutenberg styling/functionality) echo render_block( $block ); } } ?>
A quick breakdown of what this does:
parse_blocks( get_the_content() ): Takes your post's content and turns it into an array of individual Gutenberg blocks, each with its type, content, and settings.- The
foreachloop goes through every block in the post. - We check if the block is one of your target types (
video,core-embed/youtube, orhtml). - For HTML blocks, we add an optional check to make sure it actually contains video content (since admins might use HTML blocks for other things too).
render_block( $block ): Properly renders the block just like Gutenberg would, so you don't lose any built-in styling or functionality (like video controls for the core Video block).
Important Notes:
- This will output all matching blocks in the order they appear in the post. If you only want the first video block, you can add a
break;afterecho render_block( $block );. - If you're using custom embed blocks (not the core YouTube one), you'll need to add their block names to the
$target_blocksarray (e.g.,'embed/youtube'if it's a third-party block).
内容的提问来源于stack exchange,提问作者E. Given
相关产品推荐
相关产品推荐

