Support » Plugin: Post Views Counter » Sort posts by views

  • Can you help me out?

    I’m really happy with your awesome plugin, but I’m in a fix here. I want to sort posts according to their views.
    Can you help me with how to do that?

    PS: since I’ve found out that this plugin doesn’t use meta keys, I’ve no idea how to solve this issue.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You can check out the function PVC_GET_MOST_VIEWED_POSTS() in the documentation here: https://dfactory.eu/docs/post-views-counter/developers-api/

    Custom integration:

    $poular_posts = get_posts(
            array(
                'post_status'   => 'publish',
                'numberposts'   => 12,
                'post_type'     => 'post',
                'order'       => 'DESC',
                // required by PVC
                'suppress_filters' => false,
                'orderby' => 'post_views',
                'fields' => ''
            )
        );

    The only problem I’ve found with this, is that posts with 0 views don’t show up in the list at all since the meta data isn’t set until the first person views the post. You can use something like the following to add a single post view when a post with 0 views is saved:

    // Set post views to 1 on post save.
    add_action('save_post', function ($postId) {
        if ( pvc_get_post_views( $post_id = $postId ) < 1 ){
            pvc_view_post( $post_id = $postId );
        }
    });

    Hello @veggie_89
    How to use pagination for your code?

    I used other deprecated plugin. Migrated to “Post Views Counter” plugin but don’t realize how to adapt the old code to show all my posts order by post views. This is the code for the previous plugin:

    <?php 
    
    			  $paged = 1;
    			  if ( get_query_var('paged') ) $paged = get_query_var('paged');
    			  if ( get_query_var('page') ) $paged = get_query_var('page');
    
    	          $args = array(
    			   'paged' => $paged,
    			   'meta_key' => '_count-views_all',
    			   'orderby' => 'meta_value_num',
    			   'order' => 'DESC',				
    	          );
    
    	          $wp_query = new WP_Query($args); 
    
    	          if ( $wp_query ->have_posts() ) {
    
    	            $i=0; $postCount = 0; while (have_posts()) : the_post(); $i++; $postCount++;
    	                if($i==1){echo'<!--start row-fluid--><div class="row-fluid">';} 
    	                get_template_part( 'preview', get_post_format() );
    	                
    	                if($i==4 || $postCount == $wp_query->post_count){$i=0;echo'</div><!--/ row-fluid-->';}
    	            endwhile;
    
    	          }
    
                
                
                          
    
    	          wp_reset_postdata(); 
    
    	          ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.