Wordpress - get 5 popular posts by views without p

2019-02-11 12:32发布

问题:

Hi,

I have custom fields with image from posts, and I want to display the top 5 posts sorting by views. I am using WordPress, can you help me please?

Sorry for my bad English.

Thanks.

回答1:

There's one error with Xhynk's reference:

The query it runs returns posts in alphabetical order (1, 2, 20, 23, 3, 4, etc)

You just need to change

'orderby' => 'wpb_post_views_count'

to

'orderby' => 'meta_value_num'

For the top 5, use:

$popularpost  = new WP_Query(array(
    'posts_per_page' => 5,
    'meta_key' => 'wpb_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
));


回答2:

http://www.wpbeginner.com/wp-tutorials/how-to-track-popular-posts-by-views-in-wordpress-without-a-plugin/

Basically it's adding a meta field to each post - and deletes the old record when it's viewed, then replaces it with 'old record + 1'



回答3:

It is very easy. Just use this code into your functions.php

/*
 * Set post views count using post meta
 */
function setPostViews($postID) {
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '0');
    }else{
        $count++;
        update_post_meta($postID, $countKey, $count);
    }
}

put single.php

setPostViews(get_the_ID());

This is your popular post query:

   <?php
      query_posts('meta_key=post_views_count&posts_per_page=5&orderby=meta_value_num&
      order=DESC');
      if (have_posts()) : while (have_posts()) : the_post();
   ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title();
     ?></a>
   </li>
   <?php
   endwhile; endif;
   wp_reset_query();
   ?>

For details go



标签: wordpress