我有一些WordPress古腾堡模块,我想在我的主题的不同部分中显示它们。我知道如何找到该块并在我的主题模板中显示它,但我不知道如何阻止该块与循环中的其余块一起显示。
作为一个例子来说明:我有一个块,我希望在管理区域中有其他块,但我不想在循环内容中显示它。我需要一种方法来跳过它或者在正常的循环中过滤掉它。然后,我使用此代码在主题的另一个区域中输出:
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;
}
}
}上述代码的问题在于,它复制了与其他“普通”循环内容一起显示的块,并且也显示在我的新位置。你能帮我写一个函数/过滤器来阻止特定的块出现在循环中吗?
发布于 2020-07-18 21:57:38
我想通了..。
以下是过滤循环内容并从输出中删除特定块的函数,因为您已经在主题或主题模板文件中的另一个位置输出了该特定块的内容。
//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');https://stackoverflow.com/questions/62915921
复制相似问题