• Facebook Icon Link
    • Instagram Icon Link

    How to Create a Widget in WordPress.


    create a widget in wordpress

    What is a WordPress Widget?

    WordPress widgets allow you to easily add content and features to WordPress sidebars, footers and other widget-ready areas. WordPress comes with a number of basic widgets that are compatible with any theme and are easy to use through a simple drag-and-drop user interface. If you need a widget with features outside of what WordPress provides, you can build your own with just a bit of code.

    What do I Need to Create a WordPress Widget?

    Understanding of PHP.
    Text editor of your choice.
    WordPress website.

    Where do I Put the Widget Code?

    We will be writing this code in PHP. There are a number of ways to add widget code to your website:

    The Building Blocks of a WordPress Custom Widget.

    WordPress provides the WP_Widget class that we can use to create custom widgets. The WP_Widget class has about 18 functions and 4 of them are needed to build a widget. These are the functions we will use in this tutorial:

    construct: Registers basic information about the widget like a description, name and id.
    widget: Displays the content generated by the widget on the front-end of the website.
    form: Displays the form used to set options for your widget on the back-end of the website.
    update: Saves and updates the widget options to the database.

    How to Extend the WP_Widget Class.

    In order to create the custom widget’s class, we must extend the WP_Widget class and include these four functions.

    // Create the widget 
    class simple_widget extends WP_Widget{
     
    	// Constructor.
    	public function __construct(){
    	 
    	}
    	  
    	// Output widget content.
    	public function widget( $args, $instance ){
    		
    	}
    	          
    	// Output options form in the admin.
    	public function form( $instance ){
    	 
    	}
    	      
    	// Save/update widget data. Replaces old instances with new instances.
    	public function update( $new_instance, $old_instance ){
    	 
    	}
    } 
    

    How to Register a WordPress Widget.

    The register_widget() function is used to register the widget. It uses the widgets_init hook.

    // register Simple Widget
    function register_simple_widget(){
        register_widget( 'Simple_Widget' );
    }
    add_action( 'widgets_init', 'register_simple_widget' );

    How to Create a Simple WordPress Widget.

    In this tutorial, I will show you how to build a simple WordPress widget with a title field and a text area. It will have the ability to save, update, and display its contents on the front-end of the website.

    // Creates a Simple_Widget.
    class Simple_Widget extends WP_Widget{
     
    	// Constructor
        public function __construct(){
    
            $widget_options = array( 
                'description' => 'A Simple Widget with limited use.',
                'classname'  => 'simple-class',
            );
            parent::__construct('simple_widget', 'Simple Widget', $widget_options );
        }
     
    	// Outputs the widget content on the front-end
    	public function widget( $args, $instance ){
    
    		extract( $args );
            $title = apply_filters( 'widget_title', $instance['title'] );
            $text = apply_filters( 'widget_text', $instance['text'] );
    
            echo $before_widget;
            echo (!empty( $title )) ? $before_title . $title . $after_title : '';
            echo (!empty( $text )) ? $text . $after_widget : '';
    	}
     
      	// Outputs options form in the WordPress admin
        public function form( $instance ){
    
        	isset($instance[ 'title' ]) ? $title = $instance[ 'title' ] :  $title = __( 'Simple Title', 'xxx_domain' );
            isset($instance[ 'text' ]) ? $text = $instance[ 'text' ] : $text = __( 'Simple Text', 'xxx_domain' );
           
    		<p>
    		<label for="<?php echo $this->get_field_name( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
    		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
    		</p>
    
    		<p>
    		<label for="<?php echo $this->get_field_name( 'text' ); ?>"><?php _e( 'Text:' ); ?></label>
    		<textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>"><?php echo $text; ?></textarea>
    		</p>
    		
        }
     
        // Saves or updates widget data. Replaces old instances with new instances.
        public function update( $new_instance, $old_instance ){
    
            $instance = array();
            $instance['title'] = ( !empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
     		$instance['text'] = ( !empty( $new_instance['text'] ) ) ? strip_tags( $new_instance['text'] ) : '';
            return $instance;
        }
    }
    
    // register the Simple Widget
    function register_simple_widget() {
        register_widget( 'Simple_Widget' );
    }
    add_action( 'widgets_init', 'register_simple_widget' );

    Explanation of the Widget Functions.

    __construct():
    Defines the widget id, name, description and class name.

    widget():
    Takes the required $args and $instance parameters.
    $args: Contains arguments including $before_widget, $after_widget, $before_title and $after_title.
    $instance: Contains settings for this instance of the widget.
    Extracts the $args array.
    Defines $title and $text with values from the $instance array.
    The $before_widget, $after_widget, $before_title and $after_title variables contain HTML to be output. You can define these if you like, otherwise they will use the default WordPress values.
    Echos the contents of the $title and $text variables.

    form():
    Takes the required $instance array as a parameter.
    $instance: Contains settings for this instance of the widget.
    Checks the title and text variables.
    If they are defined, sets the variable to the new value.
    If they are not defined, sets the variable to the default value.
    Outputs the label and input field for the title.
    Outputs the label and textarea for the text.

    update():
    Takes the required $new_instance and $old instance parameters.
    $new_instance: Defines the new settings for this instance from input by the form() function.
    $old instance: Contains the old settings for this instance of the widget.
    Creates an $instance array.
    Checks if the $new_instance values are set.
    Defines and returns the newly-calculated value of $instance.

    Where is my Widget?

    1. Login to the WordPress admin area.
    2. In the admin sidebar, go to Appearance > Widgets.
    3. Locate your widget on the left side of the page.

     

    Additional Posts.

    Pin It on Pinterest

    Share This