通过插件在 WordPress 中的古腾堡编辑器标题中添加按钮

use*_*897 5 wordpress wordpress-gutenberg

我正在开发一个 WordPress 插件,我想将按钮添加到 gutenberg 编辑器的标题中,就像 Elementor 插件“使用 Elementor 编辑”添加的按钮一样

在此输入图像描述

谁能指导我该怎么做才能实现这一目标......提前致谢

Mik*_*oot 5

我已经检查了标题工具栏上的 Gutenberg 源代码,不幸的是现在还没有一个完美的解决方案。您可以拥有“自定义”按钮,但它们只能通过调用创建侧边栏的组件来完成,registerPlugin并且PluginSidebar按钮出现在固定/加星标侧边栏的右侧(就像 Yoast SEO 所做的那样)。

Elementor 是这样实现的:它订阅wp.data存储更改,每当发生某些事情时,它就会注入它的按钮(如果尚未注入)。仅仅因为 React 重新渲染 DOM,它最终可能会擦除按钮,因此订阅更改很重要,因此如果它擦除了自定义按钮 js 代码,只需重新注入它即可。

下面是简化的 ES5 代码,用于将自定义链接\按钮或任何自定义 HTML 注入其中(就像 Elementor 所做的那样)。

// custom-link-in-toolbar.js
// wrapped into IIFE - to leave global space clean.
( function( window, wp ){

    // just to keep it cleaner - we refer to our link by id for speed of lookup on DOM.
    var link_id = 'Your_Super_Custom_Link';

    // prepare our custom link's html.
    var link_html = '<a id="' + link_id + '" class="components-button" href="#" >Custom Link</a>';

    // check if gutenberg's editor root element is present.
    var editorEl = document.getElementById( 'editor' );
    if( !editorEl ){ // do nothing if there's no gutenberg root element on page.
        return;
    }

    var unsubscribe = wp.data.subscribe( function () {
        setTimeout( function () {
            if ( !document.getElementById( link_id ) ) {
                var toolbalEl = editorEl.querySelector( '.edit-post-header__toolbar' );
                if( toolbalEl instanceof HTMLElement ){
                    toolbalEl.insertAdjacentHTML( 'beforeend', link_html );
                }
            }
        }, 1 )
    } );
    // unsubscribe is a function - it's not used right now 
    // but in case you'll need to stop this link from being reappeared at any point you can just call unsubscribe();

} )( window, wp )
Run Code Online (Sandbox Code Playgroud)

因此,在您的主题或插件中创建一个 js 文件,然后按以下方式链接它:

add_action( 'enqueue_block_editor_assets', 'custom_link_injection_to_gutenberg_toolbar' );
 
function custom_link_injection_to_gutenberg_toolbar(){
   // Here you can also check several conditions,
   // for example if you want to add this link only on CPT  you can
   $screen= get_current_screen();
   // and then
   if ( 'cpt-name' === $screen->post_type ){
      wp_enqueue_script( 'custom-link-in-toolbar', get_template_directory_uri() . '/assets/js/custom-link-in-toolbar.js', array(), '1.0', true );   
   }
   
}
Run Code Online (Sandbox Code Playgroud)

同样,这个解决方案并不完美,因为我们只是将自定义 HTML 注入到由 Gutenberg(React) 管理的 DOM 中,但在这一点上,这似乎是实现它的唯一方法,也许将来我们会有类似过滤器或钩子允许我们注入正在工具栏中呈现的自定义组件,但目前还没有。

Elementor仍然这样做。您可以在 https://github.com/elementor/elementor/blob/master/assets/dev/js/admin/gutenberg.js检查它的代码