How to show popular posts in wordpress

Home / Wordpress / How to show popular posts in wordpress

Here I want to tech you how to get popular posts based on that post comment in wordpress withaout plugin.

Display popular posts without plugin in wordpress | Get popular posts without plugin in wordpress

To show lists of the popular posts in wordpress is very usefull features for getting post popularity wise or SEO to increase visitor or provide better output to the user.

Many plugins are available to get popular posts in wordpress but here I want to show you how to get popular posts in wordpress without plugins.

Opent function.php file and put it below code into them.

# Displays a list of popular posts
<?php
function dp_popular_posts($num, $pre='<li>', $suf='</li>', $excerpt=false) {
	global $wpdb;
	$querystr = "SELECT $wpdb->posts.post_title, $wpdb->posts.ID, $wpdb->posts.post_content FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ORDER BY $wpdb->posts.comment_count DESC LIMIT $num";
	$myposts = $wpdb->get_results($querystr, OBJECT);
	foreach($myposts as $post) {
		echo $pre;
		?><a class="title" href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title ?></a><?php
		if ($excerpt) {
			dp_attachment_image($post->ID, 'medium', 'alt="'.$post->post_title.'"');
			?><p><?php echo dp_clean($post->post_content, 85); ?>... <a href="<?php echo get_permalink($post->ID); ?>">Read More</a></p><?php
		}
		echo $suf;
	}
}
?>

Open sidebar.php file and put it below code.

<div class="sidebar">
	<h2>Popular Posts</h2>
	<ul>
		<?php dp_popular_posts(5); ?>
	</ul>
</div>	

Related Posts

Leave a Reply

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