retrieve_widgets( string|bool $theme_changed = false ): array

Validates and remaps any “orphaned” widgets to wp_inactive_widgets sidebar, and saves the widget settings. This has to run at least on each theme change.

Description

For example, let’s say theme A has a "footer" sidebar, and theme B doesn’t have one.
After switching from theme A to theme B, all the widgets previously assigned to the footer would be inaccessible. This function detects this scenario, and moves all the widgets previously assigned to the footer under wp_inactive_widgets.

Despite the word "retrieve" in the name, this function actually updates the database and the global $sidebars_widgets. For that reason it should not be run on front end, unless the $theme_changed value is ‘customize’ (to bypass the database write).

Parameters

$theme_changedstring|booloptional
Whether the theme was changed as a boolean. A value of 'customize' defers updates for the Customizer.

Default:false

Return

array Updated sidebars widgets.

Source

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 = array_merge( ...array_values( $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 ) {
		// Update the widgets settings in the database.
		wp_set_sidebars_widgets( $sidebars_widgets );
	}

	return $sidebars_widgets;
}

Changelog

VersionDescription
2.8.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.