WP Trick : Display most viewed posts first on search pages

WordPress by default, shows latest posts first on archive and search pages. Here I will show you how to sort your posts on search results page using post view counts.

Step 1. Install Lester Chan’s post views plugin.
This plugin counts every time a visitor views a single post page. Go to Plugins > Add New > Search and type wp postviews for easy install.

Step 2. Open functions.php and add the code below to the end of the file right before ?> (if there is one).

// SEARCH FILTER
function base6_search_filter( $query ) {
	if( $query->is_search ) {
		$query->set( 'v_sortby' , 'views' );
		$query->set( 'v_orderby' , 'desc' );
		add_filter('posts_fields', 'views_fields');
		add_filter('posts_join', 'views_join');
		add_filter('posts_where', 'views_where');
		add_filter('posts_orderby', 'views_orderby');
	} 
} add_filter( 'pre_get_posts' , 'base6_search_filter' );

This code filters your posts when a visitor views your search page. It sorts results by post view counts. Your most visited posts will be on top.

Step 3. Save & upload the file to your server.

If you just installed the wp-postviews plugin, it may take some time for this trick to work.

I hope you like the trick. Cheers!



NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien