WordPress The Right Way
English en-US
English en-US
  • WordPress The Right Way
  • Getting Started
  • Debugging
    • Error Logging
    • Handling Errors
    • Tools
    • Constants of wp-config.php
  • Data
  • Core
  • Code Style Guide
  • I18n
  • JavaScript
  • Multisite
  • Queries
    • User Queries
    • SQL
    • Taxonomy and Term Queries
    • Comment Queries
    • Post Queries
  • Routing
    • The Main Loop & Template Loading
    • What Are Query Variables and Where Do They Come From?
    • Clashes, Slugs, & Debugging
    • Rewrite Rules
  • Security
    • Secure HTTP
    • Standalone PHP Files
  • Servers And Deployment
    • Migrations
    • WP CLI
  • Templates
  • Testing
    • Testing Theory
      • Test Driven Development
      • Unit Testing
      • Behavior Driven Development
    • Testing Plugins
    • WP_UnitTestCase
  • Widgets
  • Community
  • Credits
Powered by GitBook
On this page
  • Enqueing a script
  • For the widget form in the admin area
  • For the frontend
  • Events
  • A New Widget is Added, or Re-ordered
  • The widget form opens
  • Further Reading

Widgets

Widgets have served WordPress well over the years, but the future is blocks. We advise only to build widgets only when it cannot be avoided. Instead, build blocks. Most widgets can be ported to server rendered blocks.

In the event that you do need to build a widget, here is some useful information:

Enqueing a script

For the widget form in the admin area

A quick note on how to do it, and a note on running the JS, so that it doesn't get ran on the html used to create new widget forms, only those in the sidebars on the right.

For the frontend

How to enqueue a widgets scripts and styles, but only if the widget is on the page

Events

Running code when:

A New Widget is Added, or Re-ordered

  • Make use of the ajaxStop event to process javascript when a widget is added or re-ordered

jQuery( document ).ready( function( $ ) {
    function doWidgetStuff() {
        var found = $( '#widgets-right .mywidgetelement' );
        found.each( function( index, value ) {
          // process elements
        } );
    }

    window.counter = 1;

    doWidgetStuff();

    $( document ).ajaxStop( function() {
        doWidgetStuff();
    } );
} );

The widget form opens

  • Some js to show how to do things when the form opens and closes

Further Reading

PreviousWP_UnitTestCaseNextCommunity

Last updated 4 years ago

Executing javascript when a widget is added