Library Technology - Reviews, Tips, Giveaways, Freeware

Library Technology – Reviews, Tips, Giveaways, Freeware

Tech tips: How to display most viewed posts first on search pages

Posted In Webmaster, WordPress, Wordpress tips - By Techtiplib on Monday, November 5th, 2012 With No Comments »

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).

Code Snippet

functionbase6_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.

Via Shailan

More contents in: ,

About - Hey, this blog belongs to me! I am the founder of TechTipLib and managing editor right now. And I love to hear what do you think about this article, leave comment below! Thank you so much...