寻找“迷失”的小部件,这必须至少在每个主题变化上运行。

原型

retrieve_widgets( string|bool $theme_changed = false )

参数

$theme_changed (string|bool) (Optional) 是否将主题更改为布尔值。 “customize”的值会延迟Customizer的更新。

返回值

(array)  更新了侧边栏小部件。

源文件

路径:wp-includes/widgets.php

<?php
...
function retrieve_widgets( $theme_changed = false ) {
	global $wp_registered_sidebars, $sidebars_widgets, $wp_registered_widgets;
	$registered_sidebars_keys = array_keys( $wp_registered_sidebars );
	$registered_widgets_ids   = array_keys( $wp_registered_widgets );
	if ( ! is_array( get_theme_mod( 'sidebars_widgets' ) ) )  {
		if ( empty( $sidebars_widgets ) ) {
			return array();
		}
		unset( $sidebars_widgets['array_version'] );
		$sidebars_widgets_keys = array_keys( $sidebars_widgets );
		sort( $sidebars_widgets_keys );
		sort( $registered_sidebars_keys );
		if ( $sidebars_widgets_keys === $registered_sidebars_keys ) {
			$sidebars_widgets = _wp_remove_unregistered_widgets( $sidebars_widgets, $registered_widgets_ids );
			return $sidebars_widgets;
		}
	}
	// Discard invalid, theme-specific widgets from sidebars.
	$sidebars_widgets = _wp_remove_unregistered_widgets( $sidebars_widgets, $registered_widgets_ids );
	$sidebars_widgets = wp_map_sidebars_widgets( $sidebars_widgets );
	// Find hidden/lost multi-widget instances.
	$shown_widgets = call_user_func_array( 'array_merge', $sidebars_widgets );
	$lost_widgets  = array_diff( $registered_widgets_ids, $shown_widgets );
	foreach ( $lost_widgets as $key => $widget_id ) {
		$number = preg_replace( '/.+?-([0-9]+)$/', '$1', $widget_id );
		// Only keep active and default widgets.
		if ( is_numeric( $number ) && (int) $number < 2 ) {
			unset( $lost_widgets[ $key ] );
		}
	}
	$sidebars_widgets['wp_inactive_widgets'] = array_merge( $lost_widgets, (array) $sidebars_widgets['wp_inactive_widgets'] );
	if ( 'customize' !== $theme_changed ) {
		wp_set_sidebars_widgets( $sidebars_widgets );
	}
	return $sidebars_widgets;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/retrieve_widgets/