• Resolved Trahald

    (@trahald)


    How do you control widget options in a plugin – e.g. adding, deleting, and editing widget options?

    Such as adding or deleted a sidebars_widgets widget, or a widget_pages widget, in the wp_options table.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter Trahald

    (@trahald)

    OK, by analyzing wp-admin/widgets.php for a while I think I was finally able to figure it out. Given some registered widget ‘my-test-widget’, I think it can be installed an uninstalled to ‘sidebar-1’ with:

    require_once(ABSPATH."wp-includes/widgets.php");
    $my_test_widget_id = "my-test-widget";
    $sidebars_widgets = wp_get_sidebars_widgets();
    install_my_test_widget();
    uninstall_my_test_widget();
    
    function install_my_test_widget() {
    	global $wp_registered_sidebars, $my_test_widget_id;
    	$sidebar = 'sidebar-1';
    
    	// These are the widgets grouped by sidebar
    	$sidebars_widgets = wp_get_sidebars_widgets();
    	if ( empty( $sidebars_widgets ) )
    	$sidebars_widgets = wp_get_widget_defaults();
    	// for the sake of PHP warnings
    	if ( empty( $sidebars_widgets[$sidebar] ) )
    	$sidebars_widgets[$sidebar] = array();
    
    	#	Add the widget to the sidebar if not already present
    	if(!in_array($my_test_widget_id, $sidebars_widgets[$sidebar]))
    	{
    		$sidebars_widgets[$sidebar][] = $my_test_widget_id;
    		wp_set_sidebars_widgets( $sidebars_widgets );
    	}
    }
    
    function uninstall_my_test_widget() {
    	global $wp_registered_sidebars, $my_test_widget_id;
    	$sidebar = 'sidebar-1';
    
    	// These are the widgets grouped by sidebar
    	$sidebars_widgets = wp_get_sidebars_widgets();
    	if ( empty( $sidebars_widgets ) )
    	$sidebars_widgets = wp_get_widget_defaults();
    	// for the sake of PHP warnings
    	if ( empty( $sidebars_widgets[$sidebar] ) )
    	$sidebars_widgets[$sidebar] = array();
    
    	if(in_array($my_test_widget_id, $sidebars_widgets[$sidebar]))
    	{
    		#	Find the index of the widget to remove
    		$key = array_search($my_test_widget_id, $sidebars_widgets[$sidebar]);
    		#	Update the option
    		unset($sidebars_widgets[$sidebar][$key]);
    		$sidebars_widgets[$sidebar] = array_values($sidebars_widgets[$sidebar]);
    		wp_set_sidebars_widgets( $sidebars_widgets );
    	}
    }
    Thread Starter Trahald

    (@trahald)

    This seems to work in WP 2.8 as well, though the code in wp-admin/widgets.php has changed.

    However it seems that if My Test Widget is now defined in a class like ‘Class My_Test_Widget’, the ‘$my_test_widget_id’ variable should have a ‘-2’ after it – e.g.
    $my_test_widget_id = 'my_test_widget-2';
    I don’t understand why this is the case.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Controlling widgets – sidebars_widgets, widgets_pages, etc.’ is closed to new replies.