Created
August 22, 2021 06:50
-
-
Save bagerathan/8d7228df11e08337aafd482273c85f45 to your computer and use it in GitHub Desktop.
[Popular posts based on post view] #wp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DIY Popular Posts @ https://digwp.com/2016/03/diy-popular-posts/ | |
function shapeSpace_popular_posts($post_id) { | |
$count_key = 'popular_posts'; | |
$count = get_post_meta($post_id, $count_key, true); | |
if ($count == '') { | |
$count = 0; | |
delete_post_meta($post_id, $count_key); | |
add_post_meta($post_id, $count_key, '0'); | |
} else { | |
$count++; | |
update_post_meta($post_id, $count_key, $count); | |
} | |
} | |
function shapeSpace_track_posts($post_id) { | |
if (!is_single()) return; | |
if (empty($post_id)) { | |
global $post; | |
$post_id = $post->ID; | |
} | |
shapeSpace_popular_posts($post_id); | |
} | |
add_action('wp_head', 'shapeSpace_track_posts'); | |
// shortcode: display diy popular posts: [diy_pop_posts num="10" cat="1,2,3"] | |
function shapeSpace_display_popular_posts($atts) { | |
extract(shortcode_atts(array( | |
'num' => 10, | |
'cat' => '', | |
), $atts)); | |
$temps = explode(',', $cat); | |
$array = array(); | |
foreach ($temps as $temp) $array[] = trim($temp); | |
$cats = !empty($cat) ? $array : ''; | |
?> | |
<h3>Popular Posts</h3> | |
<ul> | |
<?php $popular = new WP_Query(array('posts_per_page' => $num, 'meta_key' => 'popular_posts', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'category__in' => $cats)); | |
while ($popular->have_posts()) : $popular->the_post(); ?> | |
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> | |
<?php endwhile; wp_reset_postdata(); ?> | |
</ul> | |
<?php } | |
add_shortcode('diy_pop_posts', 'shapeSpace_display_popular_posts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment