wp_assign_widget_to_sidebar

The timeline below displays how wordpress function wp_assign_widget_to_sidebar has changed across different WordPress versions. If a version is not listed, refer to the next available version below.

WordPress Version: 5.9

/**
 * Assigns a widget to the given sidebar.
 *
 * @since 5.8.0
 *
 * @param string $widget_id  The widget ID to assign.
 * @param string $sidebar_id The sidebar ID to assign to. If empty, the widget won't be added to any sidebar.
 */
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);
}

WordPress Version: 5.8

/**
 * Assigns a widget to the given sidebar.
 *
 * @since 5.8.0
 *
 * @param string $widget_id  The widget id to assign.
 * @param string $sidebar_id The sidebar id to assign to. If empty, the widget won't be added to any sidebar.
 */
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);
}