Skip to content

Instantly share code, notes, and snippets.

@rodica-andronache
Created October 17, 2013 19:06
Show Gist options
  • Select an option

  • Save rodica-andronache/7030451 to your computer and use it in GitHub Desktop.

Select an option

Save rodica-andronache/7030451 to your computer and use it in GitHub Desktop.
WORDPRESS - Popular posts by number of views
In functions.php:
function cwp_set_post_views($postID) {
$count_key = 'cwp_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);
}
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function cwp_track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
cwp_set_post_views($post_id);
}
add_action( 'wp_head', 'cwp_track_post_views');
function cwp_get_post_views($postID){
$count_key = 'cwp_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';
}
In single.php:
cwp_set_post_views(get_the_ID());
Unde vreau sa afisez posturile populare:
<?php
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'cwp_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC' ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();
the_title();
endwhile;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment