函数文档

unregister_sidebar()

💡 云策文档标注

概述

unregister_sidebar() 函数用于从已注册的侧边栏列表中移除指定的侧边栏,适用于 WordPress 主题开发中动态管理侧边栏。

关键要点

  • 函数接受一个必需参数 $sidebar_id,类型为字符串或整数,表示注册时指定的侧边栏 ID。
  • 通过操作全局变量 $wp_registered_sidebars 来移除侧边栏,使用 unset() 函数实现。
  • 在子主题中使用时,需注意钩子优先级,确保在父主题注册侧边栏后执行移除操作。

代码示例

function remove_some_widgets(){
    // 移除 TwentyTen 主题注册的页脚侧边栏
    unregister_sidebar( 'first-footer-widget-area' );
    unregister_sidebar( 'second-footer-widget-area' );
    unregister_sidebar( 'third-footer-widget-area' );
    unregister_sidebar( 'fourth-footer-widget-area' );
}
add_action( 'widgets_init', 'remove_some_widgets', 11 );

注意事项

在子主题的 functions.php 文件中使用 unregister_sidebar() 时,由于子主题文件先于父主题加载,需将 widgets_init 钩子的优先级设为 11 或更高,以确保在父主题注册侧边栏后执行移除操作,避免无效调用。


📄 原文内容

Removes a sidebar from the list.

Parameters

$sidebar_idstring|intrequired
The ID of the sidebar when it was registered.

Source

function unregister_sidebar( $sidebar_id ) {
	global $wp_registered_sidebars;

	unset( $wp_registered_sidebars[ $sidebar_id ] );
}

Changelog

Version Description
2.2.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Basic Example

    If added to a child theme’s functions.php file, this will remove the footer sidebars registered by the TwentyTen theme.

    function remove_some_widgets(){
    
    	// Unregister some of the TwentyTen sidebars
    	unregister_sidebar( 'first-footer-widget-area' );
    	unregister_sidebar( 'second-footer-widget-area' );
    	unregister_sidebar( 'third-footer-widget-area' );
    	unregister_sidebar( 'fourth-footer-widget-area' );
    }
    add_action( 'widgets_init', 'remove_some_widgets', 11 );

    Notes

    In the example, note that we assign a priority of 11 when registering the widgets_init hook. This is because a child theme’s functions.php file is called before the parent theme’s, which means that our call to unregister_sidebar() would accomplish nothing since the sidebar has not yet been registered.

    By lowering the priority of our action, we ensure that it is called after the parent theme’s functions.php file is loaded.