首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >跳过循环中的某些Gutenberg块

跳过循环中的某些Gutenberg块
EN

Stack Overflow用户
提问于 2020-07-15 21:23:47
回答 1查看 495关注 0票数 1

我有一些WordPress古腾堡模块,我想在我的主题的不同部分中显示它们。我知道如何找到该块并在我的主题模板中显示它,但我不知道如何阻止该块与循环中的其余块一起显示。

作为一个例子来说明:我有一个块,我希望在管理区域中有其他块,但我不想在循环内容中显示它。我需要一种方法来跳过它或者在正常的循环中过滤掉它。然后,我使用此代码在主题的另一个区域中输出:

代码语言:javascript
复制
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;
    }
  }
}

上述代码的问题在于,它复制了与其他“普通”循环内容一起显示的块,并且也显示在我的新位置。你能帮我写一个函数/过滤器来阻止特定的块出现在循环中吗?

EN

回答 1

Stack Overflow用户

发布于 2020-07-18 21:57:38

我想通了..。

以下是过滤循环内容并从输出中删除特定块的函数,因为您已经在主题或主题模板文件中的另一个位置输出了该特定块的内容。

代码语言:javascript
复制
//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');
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62915921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档