The relation between sidebars and widgets is stored in the sidebars_widgets
option, as a serialized array that might look like this (expanded):
Array
(
[orphaned_widgets_1] => Array
(
[0] => recent-posts-2
)
[wp_inactive_widgets] => Array
(
[0] => calendar-2
)
[sidebar-1] => Array
(
[0] => recent-posts-5
[1] => text-6
[2] => text-2
[3] => search-6
[4] => text-3
)
[sidebar-2] => Array
(
[0] => text-4
)
[sidebar-3] => Array
(
[0] => text-5
[1] => recent-posts-6
[2] => search-7
)
)
WordPress uses the wp_get_sidebars_widgets()
function to fetch this relationship.
If we want to find in which sidebar e.g. the fifth instance of the Recent Posts widget ( recent-posts-5
) belongs to, then we can search the array and find that it’s the sidebar-1
sidebar.
Helper function:
We could do that with a helper function like this one:
/**
* @param string $widget_id Widget ID e.g. 'recent-posts-5'
* @return string|null $sidebar_id Sidebar ID e.g. 'sidebar-1'
*/
function wpse_get_sidebar_id_from_widget_id( $widget_id )
{
$sidebars = wp_get_sidebars_widgets();
foreach( (array) $sidebars as $sidebar_id => $sidebar )
{
if( in_array( $widget_id, (array) $sidebar, true ) )
return $sidebar_id;
}
return null; // not found case
}
In PHP 7.1 we could use ?string
as a nullable string type.
Usage example:
$sidebar_id = wpse_get_sidebar_id_from_widget_id( 'recent-post-5' );
So within your in_widget_form
callback you could try (untested):
add_action( 'in_widget_form', function( $widget_object, $return, $instance )
{
$sidebar_id = wpse_get_sidebar_id_from_widget_id( $widget_object->id );
if( is_string( $sidebar_id ) )
{
// ... do stuff ...
}
}, 10, 3 );
Update:
This seems to have been solved similarly here: How to determine which sidebar the widget has been added to, via widget admin?.