Home > OS >  How to make a popular post on wordpress with a custom theme
How to make a popular post on wordpress with a custom theme

Time:01-05

I have related post code as below

<div >Related Posts</div>
<div >
    <?php
    $related = get_posts(
        array(
            'category__in' => wp_get_post_categories($post->ID),
            'numberposts' => 6,
            'post__not_in' => array($post->ID)
        )
    );
    if( $related ) {
        foreach( $related as $post ) {
            setup_postdata($post);
            get_template_part( 'includes/templates/loop', 'single' );
        }
    }
    wp_reset_postdata();
    ?>
</div>

i found popular post codes here WP Populer Post

how to make the popular post code implemented in the code made above?

CodePudding user response:

Just use below code into your functions.php

/*
 * Set post views count using post meta
 */
function setPostViews($postID) {
    $countKey = 'post_views_count';
    $count = get_post_meta($postID, $countKey, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $countKey);
        add_post_meta($postID, $countKey, '0');
    }else{
        $count  ;
        update_post_meta($postID, $countKey, $count);
    }
}

Put setPostViews(get_the_ID()); into single.php file.

Then use below code for popular posts:

<div >Related Posts</div>
<div >
    <?php
    query_posts(
        array(
            'category__in' => wp_get_post_categories($post->ID),
            'post__not_in' => array($post->ID),
            'meta_key' => 'post_views_count',
            'posts_per_page' => '6',
            'orderby' => 'meta_value_num',
            'order' => 'DESC'
        )
    );
    if (have_posts()) :
        while (have_posts()) :
            the_post();
            get_template_part( 'includes/templates/loop', 'single' );
        endwhile;
    endif;
    wp_reset_query();
    ?>
</div>
  • Related