在循环中跳过某些古腾堡块 [英] Skip Certain Gutenberg Block in Loop

查看:35
本文介绍了在循环中跳过某些古腾堡块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some WordPress Gutenberg blocks that I want to display in a different part of my theme. I know how to find the block and display it in my theme's template, but I don't know how to stop the block from showing with the rest of the blocks in the loop.

举个例子澄清一下:我想在管理区域中有一个块和其他块,但我不想在循环内容中显示它.我需要一种方法来跳过它或在正常循环中过滤掉它.然后我用这个代码在我主题的另一个区域输出:

To clarify as an example: I have one block that I want to have in the admin area with the other blocks but I don't want to display it in the loop content. I need a way to skip it or filter it out in the normal loop. Then I use this code to output in another area of my theme:

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

上述代码的问题在于它复制了块以与另一个正常"块一起显示.循环内容以及我的新位置.你能帮我写一个函数/过滤器来阻止特定块出现在循环中吗?

The problem with the above code is it duplicates the block to show with the other "normal" loop content and also in my new location. Can you help me write a function/filter to stop specific blocks from showing up in the loop?

推荐答案

我想通了...

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

Here is the function to filter the content of the loop and remove a specific block from the output because you already outputted the content of that specific block in another location in your theme or theme template file.

//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');

这篇关于在循环中跳过某些古腾堡块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆