Switch after the 1st instance and abort
In the following example you can find a static
variable that's not set on the first instance. If the widget gets called the 1st time, we set it to true. On the 2nd run, we abort and just return
without actually serving anything to the user.
class My_Widget extends WP_Widget {
// You static instance switch
static $instance;
function My_Widget() {
// We set the static class var to true on the first run
if ( ! $this->instance ) {
$this->instance = true;
}
// abort silently for the second instance of the widget
else {
return;
}
// widget actual processes
}
function form($instance) {
// outputs the options form on admin
}
function update($new_instance, $old_instance) {
// processes widget options to be saved
}
function widget($args, $instance) {
// outputs the content of the widget
}
}
register_widget('My_Widget');
Code taken from the related Widgets API Codex article
Handling the global widgets array
Another option might be to check the global array containing all registered widgets:
function wpse32103_show_widgets()
{
$dump = '<pre>';
$dump .= var_export( $GLOBALS['wp_registered_widgets'], false );
$dump .= '</pre>';
return print $dump;
}
add_action( 'shutdown', 'wpse32103_show_widgets' );
The output of the associative array contains the name as key, appended by -2
(nr. is incremented). You could search through the array on the init
or admin_init
hook and simply unset if you have found a second instance. Maybe something like the following:
function wpse32103_show_widgets()
{
global $wp_registered_widgets;
// Go and search for your widgets name with the above written function
$target = 'FILL IN YOUR FOUND ARRAY KEY HERE. Without -2 (or any other appending number)';
// Container for your targeted widget(s)
$unsets = array();
foreach ( array_keys( $wp_registered_widgets ) as $widget )
{
// remove dashes
$widget_check = str_replace( '-', '', $widget );
// remove numbers
$widget_check = preg_replace( '/[^0-9]/', '', $widget );
// if we match, do it in our container
if ( $widget_check === $target )
$unsets[] = $widget;
}
// less than one element in the container: abort
if ( ! count ( $unsets ) > 1 )
return;
// preserve first element
array_shift( array_values( $unsets ) );
// unset all left instances from the global array
foreach ( $unsets as $unset )
unset ( $wp_registered_widgets[ $unset ] );
return;
}
add_action( 'init', 'wpse32103_show_widgets' );