WordPress.org

Ready to get started?Download WordPress

Forums

Query is not work. (3 posts)

  1. r0nin
    Member
    Posted 1 year ago #

    I use this codes in my functions.php to track post views.

    /* Functions to track Post Views*/
     function getPostViews($postID){
     $count_key = 'post_views';
     $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.' view';
     }
     function setPostViews($postID) {
     $count_key = 'post_views';
     $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);
     }
     }
    
     /* Track the Views for the post using wp_head hook */
     function trackPostViews ($post_id) {
     if ( !is_single() ) return;
     if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;
     }
     setPostViews($post_id);
     }
     add_action( 'wp_head', 'trackPostViews');

    In the admin area is all ok. Function is works fine and write post views to database.
    But i want to display my most viewed post on the sidebar and it is not work. There is dispalyed posts, but not most viewed. This is my query.

    <?php
    
     function filter_where2($where = '') {
     $where .= " AND post_date > '" . date('Y-m-d', strtotime('-10 days')) . "'";
     return $where;
     }
     if ( ! $my_paged = absint( get_query_var( 'paged' ) ) )
     $my_paged = 1;
    
     if ( ! $my_query = get_transient( "7677recent_$my_paged" ) ) 
    
     {
    add_filter('posts_where', 'filter_where2');
    $my_query = new WP_Query( "meta_key=post_views&orderby=meta_value&order=DESC&posts_per_page=5&paged=$my_paged" );
    set_transient( "7677recent_$my_paged", $my_query, 60 * 60 );
     }
     remove_filter( 'posts_where', 'filter_where2' );
     while ($my_query->have_posts()) : $my_query->the_post();
     ?>

    I just can`t understand why it is not work. This is a big puzzle for me.

  2. Marventus
    Member
    Posted 1 year ago #

    Hi, there. On a first look, your trackPostViews function is using the variable $post_id, whereas your getPostViews and setPostViews use $postID.
    Fix that and in the meantime I'll take a closer look.

  3. Marventus
    Member
    Posted 1 year ago #

    I took a deeper look and made you some suggestions. Here is my version with my comments. All my comments are marked

    /* Marv: COMMENT */

    I hope this helps a bit.
    Good night!

Topic Closed

This topic has been closed to new replies.

About this Topic