How to create popular post widgets without plugin in WordPress

How to create popular post widgets without plugin in WordPress

Do you want to create popular post widgets without a plugin in WordPress? In this article we will create popular post widgets by views. We will not use any WordPress plugin for creating widgets.

Widgets are non content elements. It’s a content block which you can add sidebar, footer and header. We already show How to Create Custom Widget

Popular post is the post which visitors like and comment on the most. Not every post is popular on a blog site. We already show Display Popular Posts by Views in WordPress Without a Plugin.

Get Post View Count:

If you read our article, You already know How to get a post view count. We will explain in short. We set a meta key when a visitor visits a post that updates his value.  It will show our popular posts by post views.

Use this code on function.php:

function wpk_set_post_views($postID) {
    $count_key = 'wpk_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

function wpk_track_post_views ($postID) {
    if ( !is_single() ) return;
    if ( empty ( $postID) ) {
        global $post;
        $postID = $post->ID;    
    }
    wpk_set_post_views($postID);

}
add_action( 'wp_head', 'wpk_track_post_views');

function wpk_get_post_views($postID){
    $count_key = 'wpk_post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}

If you using a cache plugin like the W3 Total Cache wpk_track_post_views tracker function can’t work. We solve that issue by the Fragmented Caching technique. You can use it on the single.ph like,

<!-- mfunc wpk_set_post_views($post_id); --><!-- /mfunc -->

Create Popular Post Widgets:

If you read our articles, You already know how to create a widget and how to get popular posts.  We will merge together and create a popular post widget. We are going to create a professional widget.

/**
 * Popular Posts Widgets 
 */
class WPK_PopularPost extends WP_Widget{
	
	//widgets ID, title and description
	function __construct(){
 		parent::__construct(
 			'wpk_popular_post_widgets',
 			__('WPK Popular Posts', 'textdomain'),
 			array( 'description' => __( 'Sample widget for Tutorial', 'textdomain' ), )
 		);
	}
	
	//we create output
	public function widget( $args, $instance ) {
 		$title = apply_filters( 'widget_title', $instance['title'] );
 		$display_title = (!empty($instance['display_title']))? true : false;
 		$title_html = ($title != '' && $display_title)? $args['before_title'].$title.$args['after_title']:'';
 		
 		$display_thumbnail = (!empty($instance['display_thumbnail']))? true : false;

 		$_args = array( 
			'posts_per_page' => $instance['num_of_post'], 
			'meta_key' => 'wpk_post_views_count', 
			'orderby' => 'meta_value_num', 
			'order' => 'DESC'  
		);
		$popularpost = new WP_Query($_args);

 		echo $args['before_widget'];
 		?>
 		<div class="wpk-popular-post">
 			<?php echo $title_html; ?>

 			<?php if($popularpost->have_posts()): ?>
 			<ul class="popular-post-list" style="list-style: none; margin-left: 0; padding-left: 0;">
 				<?php while ($popularpost->have_posts()): $popularpost->the_post();?>
 					<li id="popular-post-<?php echo intval(get_the_ID()); ?>" style="padding-bottom: 30px">
 						<?php if($display_thumbnail && has_post_thumbnail()): ?>
 						<img src="<?php echo get_the_post_thumbnail_url(get_the_ID()); ?>" alt="<?php the_title(); ?>">
 						<?php endif; ?>
 						<p style="margin: 0;"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
 						<span><?php the_date(); ?></span>
 					</li>
 				<?php endwhile; ?>
 			</ul>
 			<?php endif; ?>

 		</div>
 		<?php

 		echo $args['after_widget'];
	}
	
	//Admin options
	public function form( $instance ) {
 		$title = (isset($instance[ 'title' ]))? $instance[ 'title' ]:'WPKnifer Title';
 		$num_of_post = (isset($instance[ 'num_of_post' ]))? $instance[ 'num_of_post' ]:3;
 		$display_title = (isset($instance[ 'display_title' ]))? $instance[ 'display_title' ]:1;

 		?>
 		<p>
		<label for="<?php echo $this->get_field_id( '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_id( 'display_title' ); ?>"><?php _e( 'Display Widget Title:' ); ?></label> 
			<input class="widefat" id="<?php echo $this->get_field_id( 'display_title' ); ?>" name="<?php echo $this->get_field_name( 'display_title' ); ?>" type="checkbox" <?php checked($instance[ 'display_title' ], 'on'); ?> />
		</p>

		<p>
			<label for="<?php echo $this->get_field_id( 'display_thumbnail' ); ?>"><?php _e( 'Display Posts Thumbnail:' ); ?></label> 
			<input class="widefat" id="<?php echo $this->get_field_id( 'display_thumbnail' ); ?>" name="<?php echo $this->get_field_name( 'display_thumbnail' ); ?>" type="checkbox" <?php checked($instance[ 'display_thumbnail' ], 'on'); ?>/>
		</p>

		<p>
		<label for="<?php echo $this->get_field_id( 'num_of_post' ); ?>"><?php _e( 'Number of Post Display:' ); ?></label> 
		<input class="widefat" id="<?php echo $this->get_field_id( 'num_of_post' ); ?>" placeholder="Enter Number Only" name="<?php echo $this->get_field_name( 'num_of_post' ); ?>" value="<?php echo esc_attr( $num_of_post ); ?>">
		</p>
 		<?php
	}
	
	//Update value to database
	public function update( $new_instance, $old_instance ) {

 		$instance = array();
 		$instance['title'] = (!empty( $new_instance['title'])) ? strip_tags( $new_instance['title'] ) : '';
 		$instance['num_of_post'] = (!empty( $new_instance['num_of_post'])) ? intval($new_instance['num_of_post'] ) : '';
 		$instance['display_title'] = (!empty( $new_instance['display_title'])) ? $new_instance['display_title'] : '';
 		$instance['display_thumbnail'] = (!empty( $new_instance['display_thumbnail'])) ? $new_instance['display_thumbnail'] : '';
 		return $instance;
	}

}

To load widgets on WordPress use widgets_init hook:

function wpk_load_widget() {
    register_widget( 'WPK_PopularPost' );
    
    // If you want to more Widgets you can register in This place
}
add_action( 'widgets_init', 'wpk_load_widget', 10 );

You can add more options as you like and modify the design with your choice. To update design you can edit the public function widget. 

Conclusion:

This is a simple design Popular post custom widgets. We created possible options. You can use it for custom projects or client projects.  We think you ready know How to create popular post widgets without a plugin.

We hope You like this article. If you have any problem with creating custom widgets feel free to comment below. We are ready to help you.

See More:

How to Display Related Posts in WordPress Without Plugins

2 comments

  1. Thank you for sharing informative article.
    I want display post by visitor interest means based where they are coming from what they are looking for.
    I will be grateful .
    Thank you

    1. Thank You So Much.
      Recently We don’t have any article about this. But we will write an article about ” display post by visitor interest” soon. We can not share information at this moment. Because We need well research to write code and we want to share professional code. When the article will complete, We will notify you via your email.
      We will be happy if we can help you.
      WPKnifer Team

Leave a Reply

Your email address will not be published.