How do I create a widget that only allows a single instance?

How do I create a widget that only allows a single instance of a widget to be added through the WordPress interface?

The default behaviour of widgets allows multiple instances to be added.

I am using the Example code from http://codex.wordpress.org/Widgets_API

I have seen a similar question where the answer was to use the old widget code, but I would like to continue to use that more modern code if possible.

I have seen plugins such as Twitter for WordPress that give exact control over the number of instances allowed.

Thanks,
matt

5 Answers
5

I know this is a super old question, but searching for solutions 8 years later didn’t yield many results aside from this unresolved question (and a few other vague answers). Nothing I found on this site worked for me so if others arrive on this page looking for a way to limit a widget-area to single-use from a specific widget, I’ve provided the code that worked for me below. This solution is based on an article posted by Tom McFarlin. It makes use of jQuery’s sortable function to check the widgets according against criteria every time it tries to update. I made some of my own tweaks to better suit my needs.

Please note: You’ll need to replace widget_area_id with your own ID for the specific WIDGET AREA as well as widget_id with your own ID for the actual WIDGET. Place this code in an admin.js file and enqueue it on the backend.

jQuery(document).ready(function($){

    $('#widget_area_id').sortable({

        update: function( evt, ui ) {

            // Check each widget in the widget area to verify that it matches the ID of the widget we want there 
            $(this).children('.widget').each(function(){
                var value = $(this).find('.widget-inside').children('form').children('.id_base').val();
                if( value !== 'widget_id' ){
                    $(this).remove();
                }
            });

            // And if there are more than one widget, remove all but one
            if ( 2 !== $(this).children().length ) {
                $(this).children(':last').remove();
            }

        }

    });

});

Leave a Comment