WordPress custom widgets

How To Create WordPress Custom Widgets Without any plugin

Hello, today we will try to create WordPress custom widgets in WordPress Without any plugin. We only use simple PHP coding. I will provide the full code of the widgets in the post read carefully and learn it.

Popular Post Widgets

Now we are going to create popular post widgets in a simple way. The widget counts your post views automatically display post on top according to the post views. So lets start

First of all open you themes function.php

<?php 
 /*======================================
   Popular post by count views
=======================================*/   
function w3hax_save_post_views( $postID ){
	$metaKey = 'w3hax_post_views';
	$views = get_post_meta( $postID, $metaKey, true );
	$count = ( empty( $views ) ? 0 : $views );
	$count++;
	update_post_meta( $postID, $metaKey, $count );
}
 remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
 
 /*======================================
   Popular post widget
=======================================*/
 
 /**
 * Name: Popular Posts widget.
 * Author: https://www.w3templates.com
 */
class Popular_Post_Widget extends WP_Widget {

	/* Register widget with WordPress.*/
	function __construct() {
		parent::__construct(
			'popular_post_widget', // Base ID
			esc_html__( 'W3hax Popular Posts', 'text_domain' ), // Name
			array( 'description' => esc_html__( 'A Popular Post Widget', 'text_domain' ), ) // Args
		);
	}

	/**
	 * Front-end display of widget.*/
	public function widget( $args, $instance ) {		
		$title = $instance['title'];
		$posts = $instance['posts'];
		
		$posts_args = array(
		    'post_type'      =>   'post',
			'posts_per_page'  =>   $posts,
			'meta_key'       =>   'w3hax_post_views',
			'orderby'        =>   'meta_value_num',
			'order'          =>   'DESC'
		);
		$posts_query = new WP_Query( $posts_args );
		
		echo $args['before_widget'];
		
		if ( ! empty( $instance['title'] ) ) {
			echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
		}
	
		//write code for determining popular posts
		
		echo '<ul>';
		if( $posts_query->have_posts() ):
		  while( $posts_query->have_posts() ): $posts_query->the_post();
		?>

		<?php
		echo '<li><a href="' . get_permalink() . '" title="' . get_the_title() . '">' . get_the_title() . '</a></li>'; 
         ?>

		<?php
		  endwhile;
	    echo '</ul>';
        endif;
		
		echo $args['after_widget'];
	}

	/**
	 * Back-end widget form.
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		$title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'Popular Posts', 'text_domain' );
		$posts = ! empty( $instance['posts'] ) ? $instance['posts'] : esc_html__( '5', 'text_domain' );
		?>
		<p>
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?></label> 
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
			<label for="<?php echo esc_attr( $this->get_field_id( 'posts' ) ); ?>"><?php esc_attr_e( 'Number of Posts:', 'text_domain' ); ?></label> 
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'posts' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'posts' ) ); ?>" type="text" value="<?php echo esc_attr( $posts ); ?>">
		</p>
		<?php 
	}

	/* @return array Updated safe values to be saved. */
	
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';
		$instance['posts'] = ( ! empty( $new_instance['posts'] ) ) ? sanitize_text_field( $new_instance['posts'] ) : '';

		return $instance;
	}

}

// register Popular_Post_Widget widget
function register_popular_post_widget() {
    register_widget( 'Popular_Post_Widget' );
}
add_action( 'widgets_init', 'register_popular_post_widget' );


?>

Place the above code into function.php and save it. After saving the code open your themes single.php and search

<?php while ( have_posts() ) : the_post(); ?>

After search the above code past a line of code below of the line.

<?php w3hax_save_post_views( get_the_ID() ); ?>

The line display on above. This line count single post views and provide data to the function. And the function display post according to post views.

 

Leave a Reply

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