How To Create WordPress Widget Plugin

Widget is small block which perform specific function. Widget ussualy put in the sidebar or footer. You can list widgets which are ready in your wordpress from admin area Appearance ยป Widgets section in your WordPress dashboard.

To program widget here is some codes skeletons which you need to know

function your_register_widgets() {
	register_widget('your_widget_class');
}
add_action('widgets_init', 'your_register_widgets');

class your_widget_class extends WP_Widget {
	function __construct() {
	}
	function widget($args, $instance) {
	}
	function update($new_instance, $old_instance) {
	}
	function form($instance) {
	}
}
<?php
/*
Plugin Name: ZZ Widgets
Plugin URI: http://www.wpamanuke.com
Description: Sample Widgets Code
Version: 1.0.1
Author: WPAmaNuke
Author URI: https://wpamanuke.com
*/

function zz_register_widgets() {
	register_widget('zz_widget');
}
add_action('widgets_init', 'zz_register_widgets');

class zz_widget extends WP_Widget { 
	function __construct() {
		parent::__construct(
			'zz_widget', esc_html_x( 'ZZ Widget' , 'widget name', 'zz-widget' ),
			array(
				'classname' => 'zz-widget',
				'description' => esc_html__( 'ZZ Widget Post ' , 'zz-widget' ),
				'customize_selective_refresh' => true
			)
		);
	}
	function widget($args, $instance) {
		$defaults = array('title' => '', 'category' => 0, 'tags' => '', 'postcount' => 5, 'offset' => 0, 'sticky' => 1);
        $instance = wp_parse_args($instance, $defaults);
		$query_args = array();
		$query_args['ignore_sticky_posts'] = $instance['sticky'];
		if (0 !== $instance['category']) {
			$query_args['cat'] = $instance['category'];
		}
		if (!empty($instance['tags'])) {
			$tag_slugs = explode(',', $instance['tags']);
			$tag_slugs = array_map('trim', $tag_slugs);
			$query_args['tag_slug__in'] = $tag_slugs;
		}
		if (!empty($instance['postcount'])) {
			$query_args['posts_per_page'] = $instance['postcount'];
		}
		if (0 !== $instance['offset']) {
			$query_args['offset'] = $instance['offset'];
		}
	    
		$widget_posts = new WP_Query($query_args);
		echo wp_kses_post( $args['before_widget'] );
			if ($widget_posts->have_posts()) :
				$last = $widget_posts->post_count;
				$i = 0;
				if (!empty($instance['title'])) {
					$title = ! empty( $instance['title'] ) ? $instance['title'] : '';
					$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );
					echo wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] );
				}
				echo '<ul class="zz-widget-block">' . "\n";
					while ($widget_posts->have_posts()) : $widget_posts->the_post();
						 echo "<li>
						<a href='";
						the_permalink();
						echo "'>";
						the_title();  
						echo "</a>
						</li>";
					endwhile;
				echo '</ul>' . "\n";
			endif;
			wp_reset_postdata();
			
		echo wp_kses_post( $args['after_widget'] );
		
    }
	function update($new_instance, $old_instance) {
        $instance = array();
        if (!empty($new_instance['title'])) {
			$instance['title'] = sanitize_text_field($new_instance['title']);
		}
        if (0 !== absint($new_instance['category'])) {
			$instance['category'] = absint($new_instance['category']);
		}
		if (!empty($new_instance['tags'])) {
			$tag_slugs = explode(',', $new_instance['tags']);
			$tag_slugs = array_map('sanitize_title', $tag_slugs);
			$instance['tags'] = implode(', ', $tag_slugs);
		}
		if (0 !== absint($new_instance['postcount'])) {
			if (absint($new_instance['postcount']) > 50) {
				$instance['postcount'] = 50;
			} else {
				$instance['postcount'] = absint($new_instance['postcount']);
			}
		}
		if (0 !== absint($new_instance['offset'])) {
			if (absint($new_instance['offset']) > 50) {
				$instance['offset'] = 50;
			} else {
				$instance['offset'] = absint($new_instance['offset']);
			}
		}
        return $instance;
    }
    function form($instance) {
        $defaults = array('title' => '', 'category' => 0, 'tags' => '', 'postcount' => 5, 'offset' => 0, 'sticky' => 1);
        $instance = wp_parse_args($instance, $defaults); ?>
        <p>
        	<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('Title:', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo esc_attr($instance['title']); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" id="<?php echo esc_attr($this->get_field_id('title')); ?>" />
        </p>
		<p>
            <label for="<?php echo esc_attr($this->get_field_id('category')); ?>"><?php esc_html_e('Select a Category:', 'zz-widget'); ?></label>
            <select id="<?php echo esc_attr($this->get_field_id('category')); ?>" class="widefat" name="<?php echo esc_attr($this->get_field_name('category')); ?>">
            	<option value="0" <?php selected(0, $instance['category']); ?>><?php esc_html_e('All', 'zz-widget'); ?></option><?php
            		$categories = get_categories();
            		foreach ($categories as $cat) { ?>
            			<option value="<?php echo absint($cat->cat_ID); ?>" <?php selected($cat->cat_ID, $instance['category']); ?>><?php echo esc_html($cat->cat_name) . ' (' . absint($cat->category_count) . ')'; ?></option><?php
            		} ?>
            </select>
            <small><?php esc_html_e('Select a category to display posts from.', 'zz-widget'); ?></small>
		</p>
		<p>
        	<label for="<?php echo esc_attr($this->get_field_id('tags')); ?>"><?php esc_html_e('Filter Posts by Tags (e.g. lifestyle):', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo esc_attr($instance['tags']); ?>" name="<?php echo esc_attr($this->get_field_name('tags')); ?>" id="<?php echo esc_attr($this->get_field_id('tags')); ?>" />
	    </p>
        <p>
        	<label for="<?php echo esc_attr($this->get_field_id('postcount')); ?>"><?php esc_html_e('Post Count (max. 50):', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo absint($instance['postcount']); ?>" name="<?php echo esc_attr($this->get_field_name('postcount')); ?>" id="<?php echo esc_attr($this->get_field_id('postcount')); ?>" />
	    </p>
	    <p>
        	<label for="<?php echo esc_attr($this->get_field_id('offset')); ?>"><?php esc_html_e('Skip Posts (max. 50):', 'zz-widget'); ?></label>
			<input class="widefat" type="text" value="<?php echo absint($instance['offset']); ?>" name="<?php echo esc_attr($this->get_field_name('offset')); ?>" id="<?php echo esc_attr($this->get_field_id('offset')); ?>" />
	    </p><?php
    }
}

Leave a Reply

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