I’m on a nightly quest to build a custom single-use widget.
As soon as one instance of it has been added to a sidebar panel in the Customizer, its control on the Available Widgets panel should be displayed as disabled (or alternatively, disappear entirely).
This is how it would look (note the visually “disabled” widget on the right):
The custom Widget is registered and all, but I’m stuck at the single-use requirement.
Specs
- Scale is not a problem. It’s ok to assume only 1 registered sidebar. The approach can be to limit the use of the widget to either 1 per sidebar, or to 1 per all registered sidebars—both would be equally fine for now.
- The Widgets page on the back-end is not a problem. This is not required to work equally well on the Widgets page under Appearance on the back-end. It only has to work in the Customizer.
Questions
- About 250 years ago, all widgets used to be “single-use”. Does anyone know of a legit way to bring those times back and make a custom widget be used only 1x through the Widget API?
- If not (which I’m assuming after having dug through a fair amount of core files), I’d probably defer to a CSS-based approach (pointer-events, pseudo element overlay, whatever). Would any kind soul help my very limited Customizer/JavaScript knowledge with a basic approach on how to add/remove a dedicated CSS class to the widget control in the “available” panel (the one on the right) once an instance of said widget has been added/removed to the sidebar panel?
What I tried so far
- Dug through a fair chunk of core files.
- Read this, and this, but neither one seems practical.
- Tinkered with jQuery events
widget-added
,widget-updated
, andwidget-synced
, but miss an event for “widget deleted”.
Thanks tons in advance!
Update: Haven’t put my proof of concept on a public repo yet, would will do, of course.
Solution
I wrapped the solution kindly shared by kraftner below in a proof of concept plugin on GitHub.
WP_Widget
, for example: gist.github.com/westonruter/7141599