Wordpress 跳过循环中的某些古腾堡块
我有一些WordPress Gutenberg积木,我想在主题的不同部分展示。我知道如何找到块并在我的主题模板中显示它,但我不知道如何阻止块与循环中的其余块一起显示 举例说明:我有一个块,我想在管理区与其他块一起使用,但我不想在循环内容中显示它。我需要一种在正常循环中跳过它或过滤掉它的方法。然后,我使用此代码在我的主题的另一个区域中输出:Wordpress 跳过循环中的某些古腾堡块,wordpress,wordpress-gutenberg,gutenberg-blocks,Wordpress,Wordpress Gutenberg,Gutenberg Blocks,我有一些WordPress Gutenberg积木,我想在主题的不同部分展示。我知道如何找到块并在我的主题模板中显示它,但我不知道如何阻止块与循环中的其余块一起显示 举例说明:我有一个块,我想在管理区与其他块一起使用,但我不想在循环内容中显示它。我需要一种在正常循环中跳过它或过滤掉它的方法。然后,我使用此代码在我的主题的另一个区域中输出: function be_display_post_blockquote() { global $post; $blocks = parse_blocks(
function be_display_post_blockquote() {
global $post;
$blocks = parse_blocks( $post->post_content );
foreach( $blocks as $block ) {
if( 'lazyblock/area-2' === $block['blockName'] ) {
echo render_block( $block );
break;
}
}
}
上面代码的问题是它复制了块,以与其他“正常”循环内容一起显示,并且也在我的新位置显示。你能帮我写一个函数/过滤器来阻止特定的块出现在循环中吗?我知道了
这是一个过滤循环内容并从输出中删除特定块的函数,因为您已经在主题或主题模板文件的另一个位置输出了该特定块的内容
//If single block exists on page or post don't show it with the other blocks
function remove_blocks() {
// Check if we're inside the main loop in a post or page
if ( ( is_single() || is_page() ) && in_the_loop() && is_main_query() ) {
//parse the blocks so they can be run through the foreach loop
$blocks = parse_blocks( get_the_content() );
foreach ( $blocks as $block ) {
//look to see if your block is in the post content -> if yes continue past it if no then render block as normal
if ( 'lazyblock/top-of-page' === $block['blockName'] ) {
continue;
} else {
echo render_block( $block );
}
}
}
}
add_filter( 'the_content', 'remove_blocks');
不幸的是,这会使所有嵌入块(如YouTube块)停止工作。我不知道如何在YouTube和其他嵌入块中使用此功能。如果有人像我一样偶然发现此功能,请在此填写:要渲染嵌入等块,您需要在渲染块上添加内容过滤器。像这样的回声应用_过滤器('the_content',render_block($block));