What is the quickest way to make a widget?

I have some PHP code that I would like to pull out of an existing page of a template, and put into a widget so I can move it around.

What is the quickest way to create a widget?

Related posts

Leave a Reply

2 comments

  1. The Widgets API is the quickest way to make a widget that’s reusable. Example use:

    class My_Widget extends WP_Widget {
        /** 
          * PHP4 constructor
          */
        function My_Widget() {
            My_Widget::__construct();
        }
    
        /**
          * PHP5 constructor
          */
        function __construct() {
            // actual widget processes
        }
    
        /** 
          * Echo the settings update form
          *
          * @param array $instance Current settings
          */
        function form($instance) {
            // outputs the options form on admin
        }
    
        /** 
          * Update a particular instance
          *
          * @param array $new_instance New settings for this instance as input by the user via form()
          * @param array $old_instance Old settings for this instance
          * @return array Settings to save or bool (false) to cancel saving
          */
        function update($new_instance, $old_instance) {
            // processes widget options to be saved
        }
    
        /** 
          * Echo the widget content
          *
          * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget
          * @param array $instance The settings for the particular instance of this widget
          */
        function widget($args, $instance) {
            // outputs the content of the widget
        }
    }
    register_widget('My_Widget');