函数文档

wp_widgets_add_menu()

💡 云策文档标注

概述

wp_widgets_add_menu() 函数用于在 WordPress 主题主菜单中添加 Widgets 子菜单项,根据主题类型(块主题或传统主题)调整菜单顺序,并确保菜单按数字排序。

关键要点

  • 函数检查当前主题是否支持 widgets,不支持则直接返回。
  • 使用 wp_is_block_theme() 判断是否为块主题,以决定菜单项的插入位置(块主题追加,传统主题指定索引 8)。
  • 通过 ksort() 对 themes.php 子菜单进行数字排序,保持菜单顺序一致。
  • 相关函数包括 wp_is_block_theme()、current_theme_supports() 和 __(),用于主题支持和国际化。

代码示例

function wp_widgets_add_menu() {
    global $submenu;

    if ( ! current_theme_supports( 'widgets' ) ) {
        return;
    }

    $menu_name = __( 'Widgets' );
    if ( wp_is_block_theme() ) {
        $submenu['themes.php'][] = array( $menu_name, 'edit_theme_options', 'widgets.php' );
    } else {
        $submenu['themes.php'][8] = array( $menu_name, 'edit_theme_options', 'widgets.php' );
    }

    ksort( $submenu['themes.php'], SORT_NUMERIC );
}

注意事项

  • 此函数自 WordPress 2.2.0 引入,在 5.9.3 版本中更新为块主题不指定菜单顺序。
  • 仅当主题支持 widgets 时才会添加菜单项,否则函数无操作。
  • 菜单项需要 edit_theme_options 权限才能访问。

📄 原文内容

Appends the Widgets menu to the themes main menu.

Source

function wp_widgets_add_menu() {
	global $submenu;

	if ( ! current_theme_supports( 'widgets' ) ) {
		return;
	}

	$menu_name = __( 'Widgets' );
	if ( wp_is_block_theme() ) {
		$submenu['themes.php'][] = array( $menu_name, 'edit_theme_options', 'widgets.php' );
	} else {
		$submenu['themes.php'][8] = array( $menu_name, 'edit_theme_options', 'widgets.php' );
	}

	ksort( $submenu['themes.php'], SORT_NUMERIC );
}

Changelog

Version Description
5.9.3 Don’t specify menu order when the active theme is a block theme.
2.2.0 Introduced.