While developing a WordPress template, plugins will help to an extent in certain requirements. In such cases we will have to write custom functions / code for implementing the exact requirement. Here we’re explaining such a requirement. The requirement is to fetch WordPress Most Popular and Most Shared Posts and display 5 posts from each.
Here we can see how to fetch WordPress Most Popular and Most Shared Posts in simple steps.
WordPress Most Popular and Most Shared Posts
1. Steps to fetch 5 Most Popular Posts in WordPress
step 1: add the following code to functions.php (theme functions)
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); } }
step 2: add the following code AT the beginning of single.php & page.php in your template (theme)
$id = get_the_ID(); setPostViews($id);
step 3: add the following code at where you need to display the 5 most popular posts (most views)
<?php $posts = new WP_Query( array( 'posts_per_page' => 5, 'post_status' => 'publish', 'meta_key' => 'post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) ); while ( $posts->have_posts() ) : $posts->the_post(); ?> <div class="title"> <?php the_title(); ?> </div> <?php endwhile; wp_reset_postdata(); ?>
2. Steps to fetch 5 Most Shared Posts in WordPress
STEP 1: ADD THE FOLLOWING CODE TO SIngle.PHP/Page.php right after the loop starts
$obj_fb = json_decode( file_get_contents( 'http://graph.facebook.com/?id='.get_permalink() ) ); $likes_fb = $obj_fb->shares; update_post_meta($post->ID, '_kjl_fb_likes', $likes_fb, false);
STEP 2: ADD THE FOLLOWING CODE WHERE YOU NEED TO DISPLAY THE 5 MOST shared POSTS (facebook shares)
<?php $sposts = new WP_Query( array( 'posts_per_page' => 5, 'post_status' => 'publish', 'meta_key' => '_kjl_fb_likes', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) ); while ( $sposts->have_posts() ) : $sposts->the_post(); ?> <div class="title"> <?php the_title(); ?> </div> <?php endwhile; wp_reset_postdata(); ?>