How Migrate a Legacy Widget to block?

TLDR: If you wanted to update to v5.8 you don’t need to do anything to make widgets work, they won’t break if you update. There is no conversion step, no updating of code to make it work. migration is not necessary.

I’m trying to tranform legacy widgets to block, I was reading the docs, but I couldn’t understand where to put this javascript code :

If you decide that you want to port your WP_Widget widgets so that they can be used outside of widget areas, then this is the mechanism that lets you transform your old widgets into the new block you create. So it goes inside the new blocks transform section when you register it.

If you do not have a new replacement block though, then no changes are needed to continue using widgets as widgets. Anybody who has updated to 5.8 and opened the new widgets UI will see their widgets are still there, and can be added and changed. This is because the core developers added a compatibility layer so that widgets show up as legacy widget blocks.

If you did decide to create a replacement, perhaps because you plan to use full site editing or want to embed it inside posts, here are some pointers:

  • use server rendered blocks so you can port your widget rendering code directly
  • your widgets options should be ported directly to block attributes
  • you’ll need an edit component to replace your widgets form, this is probably going to require some javascript. The edit component is what the editor displays.
  • the save component is what generates the HTML that goes in the database, but if you’re rendering the HTML in PHP like I recommended, set this to null or don’t specify a save component at all. The block editor will assume you plan to use PHP for it
  • there’s a server render component, pass it the block type and the attributes and it will call the server and run your blocks PHP so you can display/preview it in the editor