Sorting posts according to view counts not working

I use the code snippet below to get views count of each post on my sidebar.php .
everything works but the sorting does not.
also it does not get 4 posts, it only shows 1 post although I’ve written 'numberposts' => 4 .
I guess the problem comes from post query. because when I’m on homepage, it shows the last post of website not in my custom post type. ( e.g. the “Hello World!” post)
when I’m in archive page, it gives the last post of my custom post type.
Can anybody find the problem ? Thanks

THE FUNCTION :

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return '0';
    }
    return $count;
}

// function to count views.
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

THE CODE I ADD TO SINGLE.PHP:

<?php setPostViews(get_the_ID()); ?>

THE CODE I USE AS POST QUERY TO GET AND SORT POSTS:

query_posts(array(
        'numberposts'  => 4,  /* get 4 posts, or set -1 for all */
        'orderby'      => 'meta_value_num',  /* this will look at the meta_key you set below */
        'meta_key'     => 'post_views_count',
        'order'        => 'DESC',
        'post_type' => array('news','database'),
        'post_status'  => 'publish'
    ));
    $myposts = get_posts( $args );
        foreach( $myposts as $mypost ) { ?>
        <a href="https://wordpress.stackexchange.com/questions/145642/<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php
        }
        wp_reset_query();
    ?>

1 Answer
1

Your code doesn’t make sense.

  1. You use query_posts(), which you should never do, but all that
    does is clobber the main query. You don’t use the clobbered query though.
  2. You then use get_posts() with an undefined (so far as code posted
    indicates) argument list, so it is not going to return what you
    expect.

I think that what you are looking for is this:

$args = array(
  'posts_per_page'  => 4,  /* get 4 posts, or set -1 for all */
  'orderby'      => 'meta_value_num',  /* this will look at the meta_key you set below */
  'meta_key'     => 'post_views_count',
  'order'        => 'DESC',
  'post_type' => array('news','database'),
  'post_status'  => 'publish'
);
$myposts = new WP_Query( $args );
if ($myposts->have_posts()) {
  while ($myposts->have_posts()) {
    $myposts->the_post(); ?>
    <a href="https://wordpress.stackexchange.com/questions/145642/<?php the_permalink(); ?>"><?php the_title(); ?></a><?php
  }
}

Leave a Comment