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

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