古登堡动态块正在返回404

时间:2019-01-13 作者:OpensaurusRex

我正在尝试创建一个动态块,并遵循文档中描述的步骤,但由于某些原因,返回的内容/wp-json/wp/v2/block-renderer/plugin-blocks/frontpage-releases?context=edit&_locale=userError loading block: No route was found matching the URL and request method 有一个JSON响应{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}} 而不是真正的街区。这是我的代码供您审阅,如果我遗漏了什么,请告诉我。谢谢

实施说明:

所有块都通过React via向下编译laravel-mix 将网页打包到assets/js/blocks.js

showBlock() 方法是在保存页面时调用的,但不是在编辑器中将其添加到页面内容时调用的,也不是从页面本身调用的当前正在测试分类法或自定义块组是否导致此问题

  • 将代码更改为不使用ob_start()/ob_get_clean() 并将其附加到$value 变量,以查看这是否导致了问题monolog/monolog 除了使用xdebug 具有的辅助对象扩展PhpStorm 调试,并查看它是否正在调用handle() 方法,但不是showBlock() 方法,保存时除外
  • BlockFactory.php:

    namespace LibraryPlugin\\Entities\\Blocks;
    
    use LibraryPlugin\\Entities\\Blocks\\Dynamic\\FrontpageReleases;
    use LibraryPlugin\\Traits\\Helpers\\LocationHelperTrait;
    
    /**
     * Class BlockFactory
     *
     * Loads all of the blocks into the editor, so that we can use them.
     * This is called from the plugin file, within the main plugin file,
     * if we are in the admin panel.
     *
     * @package LibraryPlugin\\Entities\\Blocks
     */
    class BlockFactory
    {
        use LocationHelperTrait;
    
        /**
         * BlockFactory constructor.
         *
         * This is run as soon as the plugin is being loaded and allows
         * the plugin to add all of the blocks to the `init` action, before
         * the other stages.
         *
         * @throws \\Exception
         */
        public function __construct()
        {
            $blocks = [
                ..., // Other non-dynamic blocks that work
                FrontpageReleases::class,
            ];
    
            add_filter(
                \'block_categories\',
                function ($categories, $post) {
                    return array_merge(
                        [
                            [
                                \'slug\' => \'plugin-templates\',
                                \'title\' => \'Plugin Page Templates\'
                            ],
                            [
                                \'slug\'  => \'plugin-blocks\',
                                \'title\' => \'Plugin Blocks\',
                            ],
                        ],
                        $categories
                    );
                },
                1,
                2
            );
    
            add_action(\'init\', function () {
                wp_register_script(
                    \'plugin-blocks\',
                    $this->webAsset(\'js/blocks.js\'),
                    [\'wp-blocks\', \'wp-i18n\', \'wp-element\', \'wp-editor\', \'lodash\', \'wp-components\'],
                    PLUGIN_VERSION
                );
    
                // Ensure we have the location of any assets in plugin
                wp_localize_script(\'plugin-blocks\', \'PLUGIN\', [
                    \'pluginUrl\' => PLUGIN_URI,
                ]);
    
                wp_register_style(
                    \'plugin-blocks\',
                    $this->webAsset(\'css/blocks.css\'),
                    [],
                    PLUGIN_VERSION
                );
            });
    
            foreach ($blocks as $block) {
                add_action(\'init\', [$block, \'handle\']);
            }
        }
    }
    
    FrontpageReleases.php:

    namespace LibraryPlugin\\Entities\\Blocks\\Dynamic;
    
    use LibraryPlugin\\Traits\\Helpers\\LocationHelperTrait;
    
    /**
     * Class FrontpageReleases
     *
     * This class is called during `init` action. Uses `plugin-blocks` JS
     * and CSS declared in `BlockFactory.php`. Passes a render callback to
     * make it a dynamic block.
     *
     * @package LibraryPlugin\\Entities\\Blocks
     */
    class FrontpageReleases
    {
        use LocationHelperTrait;
    
        /**
         * Register the release note blocks
         *
         * @return void
         */
        public static function handle(): void
        {
            register_block_type(
                \'plugin-blocks/frontpage-releases\',
                [
                    \'render_callback\' => [__CLASS__, \'showBlock\']
                ]
            );
        }
    
        /**
         * Render the value of the releases
         *
         * @param mixed $attributes
         *
         * @return mixed
         */
        public static function showBlock($attributes = null)
        {
            $classCount = 0;
            $value = \'\';
            try {
                $allReleases = new \\WP_Query([
                    \'post_type\' => \'page\',
                    \'posts_per_page\' => 3,
                    \'tax_query\' => [
                        \'relation\' => \'AND\',
                        [
                            \'taxonomy\' => \'release\',
                            \'field\' => \'term_id\',
                            \'terms\' => get_terms(\'release\', [\'fields\' => \'ids\'])
                        ],
                        [
                            \'taxonomy\' => \'solutions\',
                            \'field\' => \'term_id\',
                            \'terms\' => get_terms(\'solutions\', [\'fields\' => \'ids\']),
                            \'operator\' => \'NOT IN\'
                        ]
                    ],
                    \'order\'          => \'DESC\',
                    \'orderby\'        => \'release\', // Sort by custom taxonomy
                ]);
    
                if ($allReleases->have_posts()) {
                    while ($allReleases->have_posts()) {
                        $allReleases->the_post();
                        $isReleased = function_exists(\'types_render_field\')
                            ? types_render_field(\'is-released\')
                            : get_post_meta(get_the_ID(), \'wpcf-is-released\');
                        $value .= \'<div class="release-version"><a href="\' . get_the_permalink() . \'" title="\'
                            . get_the_title() . \'"><h2>\' . get_the_title() . \'</h2><p>\';
                        if (!$isReleased && $count === 0) {
                            $value .= \'Upcoming Release\';
                        }
                        if ($isReleased && $count === 0) {
                            $value .= \'Current Release\';
                            $count++;
                        } elseif ($isReleased && $count > 0) {
                            $value .= \'Previous Release\';
                            $count++;
                        }
                        $count++;
                        $value .= \'</p></a></div>\';
                    }
                }
    
                $value .= \'<div class="solution-resources">
                    <a href="/resources/">
                        <h2>Helpful Information</h2>
                        <p>Recommended Browser, Product Timeline, Maintentance Changes, Cloud Report,
                            Training Videos, etc.</p>
                    </a>
                </div>\';
            } catch (\\Exception $e) {
                // TODO: Figure out how to handle any exceptions
            }
    
            return $value;
        }
    }
    
    frontpage-releases.jsx 编译为blocks.js:

    import { PluginIcon } from \'./plugin-icon\';
    const { ServerSideRender } = window.wp.components;
    const { registerBlockType } = window.wp.blocks;
    const { __ } = window.wp.i18n;
    
    registerBlockType(\'plugin-blocks/frontpage-releases\', {
      title: __(\'Frontpage Releases\', \'library-plugin\'),
    
      icon: PluginIcon,
    
      category: \'plugin-blocks\',
    
      edit: function ({ attributes }) {
        return (
          <ServerSideRender
            block="plugin-blocks/frontpage-releases"
            attributes={attributes}
          />
        );
      },
    
      save() {
        return null;
      },
    });
    

    1 个回复
    最合适的回答,由SO网友:Alvaro 整理而成

    add\\u操作(\'enqueue\\u block\\u editor\\u assets,[$block,\'handle\'])方法以及所有其他块正在调用handle()方法。

    问题就在这里。这个register_block_type 打电话太晚了。尝试调用init 行动挂钩。

    您可以在中看到一个示例shortcode block 核心的。

    相关推荐

    Optimize shortcode callbacks

    我创建了一个插件,在我的WordPress站点中添加了一些短代码。但我是一个PHP新手,所以我相信它可能有一些错误或优化它的方法。它工作正常,显然没有问题。内存使用率为00.04MB。你能看看吗?非常感谢!add_action( \'wp_enqueue_scripts\', \'prefix_add_my_stylesheet\' ); function prefix_add_my_stylesheet() { // Respects SSL, Styl