5

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?

2 Answers 2

11

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');
2
  • Please add the input and return types. Then it would be a good minimal reference. :)
    – fuxia
    Commented Mar 9, 2012 at 18:37
  • "input and return types" for ... what?
    – EAMann
    Commented Mar 9, 2012 at 18:41
1

If you don't particularly care about having proper custom widget you can use a plugin like PHP Code Widget to run your code snippet

3
  • This is a very fast method and is relatively easy to implement. Just remember that it's not very portable (which might not matter to you anyway).
    – EAMann
    Commented Oct 20, 2010 at 4:33
  • @EAMann portable meaning across blogs / installable?
    – Joseph
    Commented Oct 20, 2010 at 13:37
  • @Joseph meaning across blogs, different sites, and different sidebars within the site. If it's a standalone widget that you dropped in the functions.php file or in a plug-in, you can take it anywhere. If it's drop-in code in a PHP Code Widget, you'll have to create a new PHP Code Widget each time and copy-paste the drop-in code.
    – EAMann
    Commented Oct 20, 2010 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.