Today i am telling you about how to create simple popular posts widget for your website. When we say popular posts, we mean the most commented posts. So let’s begin. Go to your WordPress dashborad, open theme editor(Appearance->Editor), choose functions.php file of your theme, and paste this code at the end of it:

<?php add_action("widgets_init", array('popular_posts', 'register')); class popular_posts { function control(){ echo 'Drag me'; } function widget($args){ extract( $args ); echo $before_widget; echo $before_title; ?>Most commented posts<?php echo $after_title;?> <ul> <?php global $post; $pargs = array( 'numberposts' => 10,'orderby'=> 'comment_count', ); $myposts = get_posts( $pargs ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> - <?php echo $post->comment_count; ?> comments </li> <?php endforeach; ?> </ul> <?php echo $after_widget; } function register(){ register_sidebar_widget('Popular posts', array('popular_posts', 'widget')); register_widget_control('Popular posts', array('popular_posts', 'control')); } } ?>

Save functions.php, then go to Appearance->Widgets page. You will see there new widget called Popular Posts. Drag-drop it anywhere you want in sidebar. As a result we get such view in our sidebar:

If you want you can make this widget more beautiful with graphic effects. For example let’s show this with colors. Replace above given code with this one:

<?php add_action("widgets_init", array('popular_posts', 'register')); class popular_posts { function control(){ echo 'Drag me'; } function widget($args){ extract( $args ); echo $before_widget; echo $before_title; ?>Most commented posts<?php echo $after_title;?> <ul> <?php global $post; $pargs = array( 'numberposts' => 10,'orderby'=> 'comment_count', ); $myposts = get_posts( $pargs );$max_count=0; foreach( $myposts as $post ) : setup_postdata($post); if ($max_count==0)$max_count=$post->comment_count; $r = dechex(mt_rand(0,255)); // generate the red component $g = dechex(mt_rand(0,255)); // generate the green component $b = dechex(mt_rand(0,255)); // generate the blue component $rgb = $r.$g.$b; ?> <li style="width:<?php echo 50+($post->comment_count*50)/$max_count ;?>%;background-color:#<?php echo $rgb ; ?>"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> - <?php echo $post->comment_count; ?> comments </li> <?php endforeach; ?> </ul> <?php echo $after_widget; } function register(){ register_sidebar_widget('Popular posts', array('popular_posts', 'widget')); register_widget_control('Popular posts', array('popular_posts', 'control')); } } ?>

Save functions.php again, then you will get such view on your sidebar: