WordPress.org

Ready to get started?Download WordPress

Forums

order post by view count? please help.. (2 posts)

  1. chuxxxxxlim
    Member
    Posted 2 years ago #

    Im trying to sort my posts by view count instead of alphabetical, i have pasted this code to my functions.php to count views:

    <?php 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 View";
    }
    return $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);
    }
    }
    ?>

    but i don't know what to change in my loop to sort the posts by view count. here is my loop code:

    <?php $posts=query_posts($query_string . '&orderby=title&order=asc');
     if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>

    Any help would be greatly appreciated, thanks! =)

  2. chuxxxxxlim
    Member
    Posted 2 years ago #

    Never mind, found a solution online.. surprised at how simple it was, anyway, thought i'd share it if anyone else is having the same problem

    Here is my loop that sorts posts by view count using the "views" meta key used on my site http://free-wp.com:

    <?php $posts=query_posts($query_string . 'meta_key=views&orderby=meta_value_num&order=DESC');
     if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>

Topic Closed

This topic has been closed to new replies.

About this Topic