Certified Wordpress Developer Widgets

Widgets
 


WordPress Widgets are WordPress Plugins that add visitor visual and interactivity options and features, such as sidebar widgets for post categories, tag clouds, navigation, search, etc. They were originally designed to provide a simple and easy-to-use way of giving design and structure control of the WordPress Theme to the user in the sidebar, which is now available on properly "widgetized" WordPress Themes to include the header, footer, and elsewhere in the WordPress design and structure.

Widgets require no code experience or expertise. They can be added, removed, and rearranged on the WordPress Administration Appearance > Widgets panel. The order and placement is set by the WordPress Theme in the functions.php file.

Some WordPress Widgets offer customization and options such as forms to fill out, includes or excludes of data and information, optional images, and other customization features.

The Widgets SubPanel explains how to use the various Widgets that come delivered with WordPress.

The Widgets page at Automattic explains how to 'widgetize' WordPress Themes and Plugins, and how to write WordPress Widgets.

WordPress Widgets and Plugins featuring Widget options can be found in the WordPress Plugin Directory.

Activate Widgets

To active your WordPress Theme Widget options:

  1. Go to Appearance > Widgets.
  2. Choose a Widget and drag it to the sidebar where you wish it to appear. There might be more than one sidebar option, so begin with the first one. Once in place, WordPress automatically updates the Theme.
  3. Preview the site. You should find that the "default" sidebar elements are now gone and only the new addition is visible.
  4. Return to the Widgets Panel to continue adding Widgets.
  5. To arrange the Widgets within the sidebar or Widget area, click and drag it into place.
  6. To customize the Widget features, click the down arrow in the upper right corner to expand the Widget's interface.
  7. To save the Widget's customization, click Save.
  8. To remove the Widget, click Remove or Delete.

If you change WordPress Themes, the Widgets will return to the left side of the page in the Widget Archives or Available Widgets list. You may need to add them again and rearrangement depending upon the Theme's ability to preserve other Theme's Widgets.

Using Text Widgets

The Text Widget is one of the most commonly used WordPress Widgets that comes with every WordPress installation. It allows users to add text, video, images, custom lists, and more to their WordPress sites.

To use the WordPress Text Widget:

  1. Go to Themes > Widgets in the WordPress Administration Panels.
  2. Open the sidebar, footer, or Theme section to which you wish to add the Text Widget.
  3. Find the Text Widget in the list of Widgets.
  4. Click and drag the Widget to the spot you wish it to appear.

To open and edit the Text Widget:

  1. Click the down arrow to the right of the Text Widget title.
  2. Set the Text Widget Title (optional).
  3. Add the text or HTML code to the box or edit what is currently there.
  4. Choose the option to Automatically add paragraphs to wrap each block of text in an HTML paragraph tag (recommended for text).
  5. Click Save to save the Text Widget.
  6. Click Close to close the Text Widget.
  7. Switch tabs in your browser and preview the results and make changes if necessary.

The Text Widget can hold a variety of HTML, XHTML, and multimedia links and players such as video and object embeds.

Styling the Text Widget

Standard image alignment CSS styles such as alignleft, alignright, and aligncenter apply for images.

To specifically style the various default styles of the WordPress Text Widget, use the following example:


Adding Code to the Text Widget

Basic HTML, embeds, and JavaScript are added easily to the WordPress Text Widget. Most embed codes from social sharing sites for multimedia will work in a WordPress Text Widget. However, active code and programming languages such as PHP will not work as the Widget will strip out code it cannot display.

To add active code to the Text Widget, use one of the many WordPress Plugins from the WordPress Plugin Directory that override WordPress restrictions on using PHP in posts. Check that they will work on Widgets as some will not.

Using RSS Widgets

There are two built-in WordPress RSS or Feed Widgets. The RSS Links displays a list of the links to various core WordPress feeds on your site for Posts and Comments. The RSS allows you to integrate an external feed source for content into a Widget area of your site, such as your Twitter account, Facebook posts, Google+ posts, or other blogs.

The RSS Links Widget offers the option to title the section and choose which type of feeds to offer to visitors to add to their feed reader. This widget does not display feed content, just the links to the feeds.

  1. Posts will displays the most recently published content in their feed reader.
  2. Comments displays the most recent comments in their feed reader.
  3. Posts and Comments displays a combination of both in their feed reader.

The visitor will typically click the link to add the feed to their feed reader.

The RSS Widget displays the most recently published content from any source with an active feed. This is an ideal way of integrating outside content into your site.

By default, WordPress RSS Widgets display the post title or the first 100 or so characters of a Tweet or long untitled post. These are either in the form of a link or features a link to the original source depending upon the feed's design and structure.

  1. Enter the RSS feed URL in the first form, copied from the source page for the content you wish to include in your sidebar or other widgetized space.
  2. Give the feed a title: This is optional and gives you the chance to showcase the source of the content.
  3. How many items would you like to display: By default, 10 are show, but you can choose from 1-20 posts.
  4. Display item content?: This allows you to show an excerpt of the content not just the title.
  5. Display item author if available?: If you wish to give credit to the original author of the content, check this to display the author.
  6. Display item date?: If available, the date of the original content will be shown.

Example Widget

We will be building a WordPress widget/plugin which will display an empty text box in the home page were users can input some text. Once the input text is submitted, it will be stored in our custom table.

Time to get our hands dirty. Let us first start with the plugin part. First step towards writing a plugin, is to enable WordPress to display the plugin in it’s plugin configuration page, so that the admin can activate the plugin. Create a folder called my-plugin inside the WordPress plugin folder. Inside my-plugin create a file called my-plugin.php and add the following to the header.

01     02    /*
03    Plugin Name: My Plugin
04    Plugin URI: {URI where you plan to host your plugin file}
05    Description: A plugin built as part of WordPress plugin tutorial.
06    Version: 1
07    Author: {Your name}
08    Author URI: {Your home page}
09    */
10    ?>

Now go to WordPress plugin configuration page and you should see “My Plugin” displayed as one of the plugins along with all other plugins that you have.

Now let us spice it up. This plugin once activated will create a custom table in WordPress DB to store the user text. Create a function that has to be run when an user activates the plugin.

Add the below to my-plugin.php

1    register_activation_hook( __FILE__, 'my_plugin_install' );
2    
3    my_plugin_install() {
4    }

Above, we have created a function called my_plugin_install which we have registered with WordPress. Now when an user activates “My Plugin”, my_plugin_install function will be run.

Now, let us add some code to create our table.

01    global $my_plugin_table;
02    global $my_plugin_db_version;
03    global $wpdb;
04    $my_plugin_table = $wpdb->prefix . 'my_plugin';
05    $my_plugin_db_version = '1.0';
06    
07    register_activation_hook( __FILE__,  'my_plugin_install' );
08    
09    function my_plugin_install() {
10      global $wpdb;
11      global $my_plugin_table;
12      global $my_plugin_db_version;
13    
14      if ( $wpdb->get_var( "show tables like '$my_plugin_table'" ) != $my_plugin_table ) {
15        $sql = "CREATE TABLE $my_plugin_table (".
16             "id int NOT NULL AUTO_INCREMENT, ".
17             "user_text text NOT NULL, ".
18             "UNIQUE KEY id (id) ".
19                 ")";
20    
21        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
22        dbDelta( $sql );
23    
24        add_option( "my_plugin_db_version", $my_plugin_db_version );
25      }
26    }

So, what does the above code do?
It checks as to whether there is a table by the name $my_plugin_table. If it is present, then does nothing. If not, creates the table and adds the table version to the options so that we can use it next time in case we want to modify the table in an upcoming release. For a detailed explanation of table creation, check this WordPress documentation. Make sure that all the variables that you have declared outside the install function are global. If they are not global, the function will not be able to read them. Check this out for the reason.

Now, activate the plugin. Once activated, see whether your new table is listed in WordPress DB.

Now for the widget creation part. Add the below code to my_plugin.php file.

01    class MyWidget extends WP_Widget {
02      function MyWidget() {
03        parent::WP_Widget( false, $name = 'My Widget' );
04      }
05    
06      function widget( $args, $instance ) {
07        extract( $args );
08        $title = apply_filters( 'widget_title', $instance['title'] );
09        ?>
10    
11        12        echo $before_widget;
13        ?>
14    
15        16          if ($title) {
17        echo $before_title . $title . $after_title;
18          }
19        ?>
20    
21       


22         
23         
24       

25    
26         27           echo $after_widget;
28         ?>
29         30      }
31    
32      function update( $new_instance, $old_instance ) {
33        return $new_instance;
34      }
35    
36      function form( $instance ) {
37        $title = esc_attr( $instance['title'] );
38        ?>
39    
40       


41         
44       


45        46      }
47    }
48    
49    add_action( 'widgets_init', 'MyWidgetInit' );
50    function MyWidgetInit() {
51      register_widget( 'MyWidget' );
52    }

I am not going to explain the above, as it is almost a copy past from this.

Now, when you go to your widget addition screen, you should see “My Widget” as one of the widgets. Drag and drop it to the right side bar, give it a title and save it. Go to your home page and you should see your widget in the right side bar.

As of now, our widget does nothing, other than display a text box to the end user. Now comes the part where you send the user input to the back end using AJAX and persist it in the database. This is not properly documented in WordPress and I had a pretty tough time figuring it out.

For AJAX, we will be using jQuery JavaScript framework. We do not have to do anything to include jQuery, as it is already enabled in WordPress. All we have to do is, use jQuery in no conflict mode.

Now we need two functions, one for the JavaScript custom code that has to be included in the home page, the other for the AJAX action.

Let us start off with the back end code.

1    function my_widget_action() {
2      global $wpdb;
3      global $my_plugin_table;
4      $user_text =  $wpdb->escape( $_POST['user_text'] );
5      $query = "INSERT INTO $my_plugin_table (user_text) VALUES ('$user_text')";
6      $wpdb->query( $query );
7      echo 'success';
8    }

The above code, takes the user input text from post and stores it in DB. Now we have to make WordPress aware of the fact that, the above function should be executed for the AJAX request. We do this by adding the below to my_plugin.php file.

1    add_action( 'wp_ajax_my_widget_action', 'my_widget_action' );
2    add_action( 'wp_ajax_nopriv_my_widget_action', 'my_widget_action' );

In the above, the part ‘wp_ajax_’ and ‘wp_ajax_nopriv’ have to be named as they. The part after that can be named whatever you want, but has to correspond with your AJAX action parameter. This will become more clear once you see the custom JavaScript code. We have two actions, ‘wp_ajax_’ and ‘wp_ajax_nopriv’, one for the logged in user and the other for the end user.

Now for the custom JavaScript code to be included in the home page.

01    add_action( 'wp_head', 'my_plugin_js_header' );
02    
03    function my_plugin_js_header() {
04      ?>
05      
14      15    }

In the above using the usual jQuery $ will not work.

The most interesting part in the above is this

    jQuery.post(”, { ‘action’: ‘my_widget_action’, ‘user_text’: jQuery(‘#my_text’).val() });

The name admin-ajax.php is misleading, but this is the url you have to use for all AJAX actions, irrespective of whether they are admin actions or end user facing ones. Also, the action should correspond to the part following ‘wp_ajax_’ and ‘wp_ajax_nopriv’, that we saw above.

Now when you enter a text in the input box and press submit, it should get persisted in the database.

 For Support