WordPress Display Popular Posts by Category ID Dynamically: A Step Guide – WordPress Tutorial

By | August 23, 2020

It is very easy to display popular posts in wordpress, we can use WordPress Popular Posts plugin. Here is the tutorial:

Display WordPress Popular Posts with WordPress Popular Posts – WordPress Plugin

However, this plugin can not allow us to display popular posts by category ids dynamically. For example, if you are reading a post in python category, you want to display popular posts in python category. Meanwhile, you are reading a tutorial in tensorflow, you should list popular posts in tensorflow category.

Dispay popular post by category id statically

WordPress Popular Posts plugin can not implement the function above, it only can allow us to display popular posts in a static category.

You can set the category ids in wordpress Widgets page.

WordPress Popular Posts plugin display popular posts by category id

How to dispay popular post by category ids dynamically

In order to make WordPress Popular Posts plugin display popular posts by category ids dynamically, we should modify this plugin.

1.Open wordpress-popular-posts\includes\class-wordpress-popular-posts-widget.php file

Then we can modify it.

2. Add code below in public function get_popular( $instance = null )

                $cats = '';
		if(is_single()){
	 		$categories = get_the_category();
			if (!empty( $categories ) ) {
				foreach( $categories as $category ){
					if($cats==""){
						$cats.=$category->term_id;
					}else{
						$cats.=",".$category->term_id;
					}
				}
				if (!empty($options['term_id']) ){
					$instance['term_id'] = $cats;
				}else{
					$instance['term_id'] .= ",".$cats;
				}
			}
	 	}
		if(is_category()){
			$cat = get_category(get_query_var('cat'));
			if (!empty($options['term_id']) ){
				$instance['term_id'] = $cat->term_id;
			}else{
				$instance['term_id'] .= ",".$cat->term_id;
			}
		}

Save it.

Then you will find this plugin can display popular posts by category ids in single and category page.

Here is the effect of this plugin.

Single page

wordpress popular posts in matplotlib

Category page

wordpress popular posts in tensorflow

Leave a Reply