Wordpress popular posts without using plugins

前端 未结 1 1906
南旧
南旧 2020-12-12 00:09

I\'m working on a site trying to get a popular posts section on it. I\'ve tried plugins but they require wp_head() and that destroys the jCarousel that I have on the site. I

相关标签:
1条回答
  • 2020-12-12 01:02

    Pleace this in functions.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);
        }
    }
    

    Next, place this where you'd like to return the post list w/views:

    <ul>
        <?php
        global $post;
        $args = array( 'numberposts' => 5, 'offset'=> 1, 'category' => 1 );
        $myposts = get_posts( $args );
        foreach( $myposts as $post ) :  setup_postdata($post); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <li><?php setPostViews(get_the_ID()); echo getPostViews(get_the_ID());; ?></li>
        <?php endforeach; ?>
    </ul>
    
    0 讨论(0)
提交回复
热议问题