WordPress.org

Ready to get started?Download WordPress

Forums

Sort posts by "Popular" - What is wrong with this code? (3 posts)

  1. findlay70
    Member
    Posted 7 months ago #

    I'm trying to sort my posts by popular. This will be defined as the most viewed posts in the last 2 days. The following code doesn't work and I cannot figure it out:

    WP_Query( array('ignore_sticky_posts' => 1, 'showposts' => 5, 'days' => 2, 'orderby' => 'meta_value_num', 'order' => 'desc') );

    I currently have this set for most viewed in total and it works:
    WP_Query( array('ignore_sticky_posts' => 1, 'showposts' => 5, 'meta_key' => '_count-views_all', 'orderby' => 'meta_value_num', 'order' => 'desc') );

    I have tried this and it doesn't work either
    WP_Query( array('ignore_sticky_posts' => 1, 'showposts' => 5, 'meta_key' => '_count-views_all', 'days' => 2, 'orderby' => 'meta_value_num', 'order' => 'desc') );

    Can anyone advise what is wrong with this.. Thanks in advance !

  2. Tokant
    Member
    Posted 7 months ago #

    I use this in my functions.php:

    function wpb_set_post_views($postID) {
        $count_key = 'wpb_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);
        }
    }
    //To keep the count accurate, lets get rid of prefetching
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
    
    function wpb_track_post_views ($post_id) {
        if ( !is_single() ) return;
        if ( empty ( $post_id) ) {
            global $post;
            $post_id = $post->ID;
        }
        wpb_set_post_views($post_id);
    }
    add_action( 'wp_head', 'wpb_track_post_views');

    Then to retrieve the 6 most popular posts i use:

    <?php
    			$args = array(
    				'posts_per_page' => 6,
    				'meta_key' => 'wpb_post_views_count',
    				'orderby' => 'meta_value_num',
    				'order' => 'DESC'
    			);
    			$query = new WP_Query( $args );
    			if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
    			?>

    As you can see the function uses wpb_post_views_count, while you use _count-views_all, so it should work. However, you are using 'showposts' instead of 'posts_per_page'. Maybe that is the problem?

  3. Tokant
    Member
    Posted 7 months ago #

    The WordPress documentation states that showposts is deprecated:
    http://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters.

    And days is not a parameter.

Reply

You must log in to post.

About this Topic

Tags