[wp-hackers] Can you execute JS when adding a Widget?

Michael D Adams mda at blogwaffe.com
Tue Aug 3 06:21:05 UTC 2010


On Mon, Aug 2, 2010 at 1:41 PM, Christopher Ross <cross at thisismyurl.com> wrote:
> Is there a way to execute JavaScript when a Widget is added?

You can try taking over the wpWidgets.save function.  The function's
call signature when adding a new widget looks a little fragile, but
this seems to work.

I tested it with the core calendar widget by replacing the 'my_widget'
id_base in the JS below with 'calendar'.


/*
Plugin Name: JS Callback for My Widget
*/

function my_widget_add_js_callback() {
?>
<script type="text/javascript">
/* <![CDATA[ */
jQuery( function($) {
var origSave = wpWidgets.save;
wpWidgets.save = function( widget, del, animate, order ) {
        if (
                // It's one of my widgets
                'my_widget' == widget.find( 'input[name=id_base]' ).val()
        &&
                // This seems to be the signature of a just added widget
                !del && !animate && order
        ) {
                alert( 'Widget Added!' );
                // Do something
        }
        origSave.call( wpWidgets, widget, del, animate, order );
}
} );
/* ]]> */
</script>
<?php
}

add_action( 'admin_head-widgets.php', 'my_widget_add_js_callback' );


More information about the wp-hackers mailing list