钩子文档

mce_buttons_2

💡 云策文档标注

概述

mce_buttons_2 是一个 WordPress 过滤器,用于自定义 TinyMCE 编辑器第二行工具栏按钮(在可视化标签页中)。开发者可以通过此 Hook 添加、移除或重新排列按钮,以优化编辑体验。

关键要点

  • 过滤器名称:mce_buttons_2,用于修改 TinyMCE 第二行按钮列表。
  • 参数:$mce_buttons_2(按钮数组)和 $editor_id(编辑器标识符,如 'content' 或 'classic-block')。
  • 用途:常用于添加样式选择器、移除颜色选择器等自定义操作。
  • 版本历史:WordPress 3.3.0 添加了 $editor_id 参数,2.0.0 引入此过滤器。

代码示例

// 添加样式选择器到工具栏开头
add_filter( 'mce_buttons_2', 'myplugin_tinymce_buttons' );

function myplugin_tinymce_buttons( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}
// 移除文本颜色选择器
add_filter( 'mce_buttons_2', 'myplugin_tinymce_buttons' );

function myplugin_tinymce_buttons( $buttons ) {
    $remove = 'forecolor';
    if ( ( $key = array_search( $remove, $buttons ) ) !== false )
        unset( $buttons[$key] );
    return $buttons;
}
// 同时移除多个按钮
add_filter( 'mce_buttons_2', 'myplugin_tinymce_buttons' );

function myplugin_tinymce_buttons( $buttons ) {
    $remove = array( 'formatselect', 'forecolor' );
    return array_diff( $buttons, $remove );
}

📄 原文内容

Filters the second-row list of TinyMCE buttons (Visual tab).

Parameters

$mce_buttons_2array
Second-row list of buttons.
$editor_idstring
Unique editor identifier, e.g. 'content'. Accepts 'classic-block' when called from block editor’s Classic block.

Source

$mce_buttons_2 = apply_filters( 'mce_buttons_2', $mce_buttons_2, $editor_id );

Changelog

Version Description
3.3.0 The $editor_id parameter was added.
2.0.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example Migrated from Codex:

    The example below will reveal the hidden “Styles” dropdown in the advanced toolbar.

    add_filter( 'mce_buttons_2', 'myplugin_tinymce_buttons' );
    
    function myplugin_tinymce_buttons( $buttons ) {
          //Add style selector to the beginning of the toolbar
          array_unshift( $buttons, 'styleselect' );
    
          return $buttons;
     }

  2. Skip to note 4 content

    Example Migrated from Codex:

    The example below will remove the text color selector from the advanced toolbar.

    add_filter( 'mce_buttons_2', 'myplugin_tinymce_buttons' );
    
    function myplugin_tinymce_buttons( $buttons ) {
          //Remove the text color selector
          $remove = 'forecolor';
    
          //Find the array key and then unset
          if ( ( $key = array_search( $remove, $buttons ) ) !== false )
    		unset( $buttons[$key] );
    
          return $buttons;
     }

    Or, if you want to remove more buttons at the same time:

    add_filter( 'mce_buttons_2', 'myplugin_tinymce_buttons' );
    
    function myplugin_tinymce_buttons( $buttons ) {
    	//Remove the format dropdown select and text color selector
    	$remove = array( 'formatselect', 'forecolor' );
    
    	return array_diff( $buttons, $remove );
     }