wp_assign_widget_to_sidebar() WordPress Function

The wp_assign_widget_to_sidebar() function is used to add a widget to a sidebar. This function takes two arguments: the sidebar ID and the widget ID.

wp_assign_widget_to_sidebar( string $widget_id, string $sidebar_id ) #

Assigns a widget to the given sidebar.


Parameters

$widget_id

(string)(Required)The widget ID to assign.

$sidebar_id

(string)(Required)The sidebar ID to assign to. If empty, the widget won't be added to any sidebar.


Top ↑

Source

File: wp-includes/widgets.php

function wp_assign_widget_to_sidebar( $widget_id, $sidebar_id ) {
	$sidebars = wp_get_sidebars_widgets();

	foreach ( $sidebars as $maybe_sidebar_id => $widgets ) {
		foreach ( $widgets as $i => $maybe_widget_id ) {
			if ( $widget_id === $maybe_widget_id && $sidebar_id !== $maybe_sidebar_id ) {
				unset( $sidebars[ $maybe_sidebar_id ][ $i ] );
				// We could technically break 2 here, but continue looping in case the ID is duplicated.
				continue 2;
			}
		}
	}

	if ( $sidebar_id ) {
		$sidebars[ $sidebar_id ][] = $widget_id;
	}

	wp_set_sidebars_widgets( $sidebars );
}


Top ↑

Changelog

Changelog
VersionDescription
5.8.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.