How To Create WordPress Widgets

How To Create WordPress Widgets

In this article, we’ll learn How To Create WordPress Widgets

WordPress widgets are powerful tools that allow you to easily add dynamic content and functionality to your website’s sidebars, footers, or any widget-ready areas.

Whether you want to display recent posts, social media feeds, or custom content, wordpress widgets provide a user-friendly way to enhance your WordPress site without diving into complex coding.

We will take you on a journey to discover the magic of create WordPress widgets, empowering you to personalize and enrich your website’s user experience.

What is WordPress Widgets

WordPress (WP) widgets is a some blocks of content that you can add to your site’s sidebars, footers, and other areas.

Widgets are drag-and-drop content areas that present data or an user interface to the user.

How to use WordPress Widgets

In WordPress Dashboard, navigate to Appearance » Widgets.

Next step, drag and drop the widgets you want to display to area (Header, Footer, Sidebar…) on the right side (enter, setup widget content and click Save button at the end of widget). Go to the front page and see it.

That’s basic steps to using Widget for you.

How to Create WordPress Widgets:

To create wordpress widget, you need to do the following:

  1. Create your widget’s class by extending the standard WP_Widget class and some of its functions.
  2. Register your widget so that it’s made available in the Widgets screen.
  3. Make sure that your theme has at least one widget area in which to add the widgets.

Your Widget Class

The WP_Widget class is located in wp-includes/class-wp-widget.php

<?php

class My_Widget extends WP_Widget {

public function __construct() {
// actual widget processes
}

public function widget( $args, $instance ) {
// outputs the content of the widget
}

public function form( $instance ) {
// outputs the options form in the admin
}

public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}

?>

The documentation for each of these functions can be found in the widget class code:

  1. construct: Set up your widget with a description, name, and display width in your admin.
  2. widget: Process the widget options and display the HTML on your page. The $args parameter provides the HTML you can use to display the widget title class and widget content class.
  3. form: Display the form that will be used to set the options for your widget. If your widget doesn’t have any options, you can skip this function (although it is still best practice to include it even if it’s empty).
  4. update: Save the widget options to the database. If your widget doesn’t have any options, you can skip this function (although it is still best practice to include it even if it’s empty).

Registering a WordPress Widgets

The register_widget() function is used to register a widget.

Call this function using the widgets_init hook:


<?php
add_action( 'widgets_init', 'wpdocs_register_widgets' );

function wpdocs_register_widgets() {
register_widget( 'My_Widget' );
}
?>

  • The HTML that wraps the widget, as well as the class for the title and widget content, is specified at the time you register the widget area using register_sidebar().

Widget Code

You can create wordpress widget by 2 ways

1. Using Plugin

2. Using functions.php file of your child theme

In following example, we’ll create wordpress widget using plugin

Start by creating a new .php file in your wp-content/plugins directory. Call your file whatever you like, but I’m going with random-post-widget.php

Paste the following into the file and save. Feel free to change the section at the top with my name in it, but don’t adjust the rest of the code yet. This is basically a skeleton empty widget, and you can see where it says //WIDGET CODE GOES HERE is where we will add our functionality later.

 <?php  /* Plugin Name: Random Post Widget  Plugin URI: uri for plugin website  Description: Random Post Widget grabs a random post and the associated thumbnail to display on your sidebar  Author: your name  Version: 1  Author URI: your website url */  class RandomPostWidget extends WP_Widget { function RandomPostWidget() { $widget_ops = array('classname' => 'RandomPostWidget', 'description' => 'Displays a random post with thumbnail' ); $this->WP_Widget('RandomPostWidget', 'Random Post and Thumbnail', $widget_ops); } function form($instance) { $instance = wp_parse_args( (array) $instance, array( 'title' => '' ) ); $title = $instance['title']; ?> <p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p> <?php } function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = $new_instance['title']; return $instance; } function widget($args, $instance) { extract($args, EXTR_SKIP); echo $before_widget; $title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']); if (!empty($title)) echo $before_title . $title . $after_title;;  // WIDGET CODE GOES HERE  echo "<h1>This is my new widget!</h1>"; echo $after_widget; } }  add_action( 'widgets_init', create_function('', 'return register_widget("RandomPostWidget");') );?> 

As it is, the plugin doesn’t do much apart from printing out a large title with the words “This is my new widget!“.

It does however give you the option to change the title, which is kind of essential for any wordpress widgets. Adding in other options is a bit beyond the scope of this article today, so for now, let’s move on to give it a real purpose.

A New Query & The Loop

To make a new query to your blog database, you need to use the query_posts() function along with a few parameters, then run through the output using a while loop. Let’s try this – a very basic query and loop to demonstrate. Replace the line of code that says:

This is my new widget!

with the following:

 // WIDGET CODE GOES HERE query_posts(''); if (have_posts()) : while (have_posts()) : the_post(); the_title(); endwhile; endif; wp_reset_query(); 

This is an absolutely basic query using default options and zero formatting of the output. Depending on how your blog is set up, the default will most likely be to grab the 10 latest posts – then all the above code does is to output the title of each post. It’s pretty ugly, but it works:

We can make it a little better right away just by adding some HTML formatting to the output with the ECHO command, and creating a link to the post using the get_the_permalink() function:

 query_posts(''); if (have_posts()) : echo ""; while (have_posts()) : the_post(); echo "".get_the_title().""; endwhile; echo ""; endif; wp_reset_query();

Already, it’s looking much better. But we only want one post, picked at random. To do this, we specify some parameters in the query:

 query_posts('posts_per_page=1&orderby=rand'); 

Of course, you could change it to any number of posts – in fact, there’s a whole range of extra bits you can pass into the query in order to restrict, expand, or change the order of the results, but let’s stick with that for now. If you refresh, you should see just one post which is randomized each time you refresh.

Now for the featured thumbnail. Replace the code with this, hopefully, you can see where we are grabbing the thumbnail and displaying it:

 query_posts('posts_per_page=1&orderby=rand'); if (have_posts()) : echo ""; while (have_posts()) : the_post(); echo "".get_the_title(); echo the_post_thumbnail(array(220,200)); echo ""; endwhile; echo ""; endif; wp_reset_query(); 

You made it. Source From: http://www.makeuseof.com/

Congratulations! You have successfully created WordPress widgets. By following these steps, you now have the power to personalize your website’s sidebars and widget-ready areas with dynamic and engaging content.

Remember, WordPress widgets offer endless possibilities to showcase your creativity and provide valuable functionality to your visitors.

So go ahead, experiment, and unleash the full potential of create WordPress widgets to enhance your website’s user experience. Happy widgetizing!

Hope this article helps to create WordPress widgets!

One thought on “How To Create WordPress Widgets

  1. Wow that was odd. I just wrote an incredibly long comment
    but after I clicked submit my comment didn’t appear.
    Grrrr… well I’m not writing all that over again.
    Anyway, just wanted to say superb blog!

Write a Reply or Comment

Your email address will not be published. Required fields are marked *