【问题标题】:Get Gutenberg Blocks without the_content()获取没有 the_content() 的 Gutenberg Blocks
【发布时间】:2019-11-27 14:58:01
【问题描述】:

我正在尝试在另一个帖子中显示来自特定帖子 ID 的古腾堡块。

问题是,是否存在可以从一篇文章中获取所有块并将其显示在站点中的任何位置的功能?就像 get_the_content 一样?

【问题讨论】:

    标签: php wordpress wordpress-gutenberg gutenberg-blocks


    【解决方案1】:

    我认为您可以使用这种方式获得古腾堡的块。

    $post_id = 1;
    $post = get_post( $post_id ); 
    
    if ( has_blocks( $post->post_content ) ) {
        $blocks = parse_blocks( $post->post_content );
        print'<pre>';print_r($blocks);print'</pre>';
        foreach( $blocks as $block ) {
            echo render_block( $block );
        }
    }
    

    注意:我没有自己测试过代码。

    【讨论】:

    • 嘿萨米!好的,我有一个带有块的数组!但是有没有什么方法可以显示块而不需要布局数组呢?
    • @LedilsonMotta 请立即检查代码。我添加了foreach 循环并在其中渲染块。您也可以从中删除print
    • 快到了!正确渲染了大部分块,但某些块(例如 You Tube 和 Soundcloud)没有渲染,只是显示了 url。我认为这是因为我们没有使用包含在 the_content() 标记中的 apply_filters()。你已经帮了我很多,我对你给我的解决方案很好,但如果你想完全解决这个问题,请随意!
    • @LedilsonMotta 过滤器可以应用于render_blockdeveloper.wordpress.org/reference/hooks/render_block
    • 出现错误。我可以看到 apply_filters 在函数 render_block() 内,这里是:developer.wordpress.org/reference/functions/render_block。如何在上面的示例中使用 apply_filters
    【解决方案2】:
    $post_id = 1; // ID of the post
    // parse_blocks parses blocks out of
    // a content string into an array
    $blocks = parse_blocks( get_the_content( $post_id ) );
    $content_markup = '';
    foreach ( $blocks as $block ) {
        // render_block renders a single block into a HTML string
        $content_markup .= render_block( $block );
    }
    // this will apply the_content filters for shortcodes
    // and embeds to contiune working
    echo apply_filters( 'the_content', $content_markup );
    

    【讨论】:

    • @ggorlen 上面的代码就是基于这个函数do_blocks
    • 谢谢,cmets 帮助澄清了代码,将链接作为编辑扔到帖子中也不错。
    猜你喜欢
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2019-03-07
    • 1970-01-01
    • 2019-07-20
    • 2020-06-07
    相关资源
    最近更新 更多