Last active
February 28, 2017 08:27
-
-
Save webhasan/8685771 to your computer and use it in GitHub Desktop.
wp: post view count
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
/** | |
* Function for post counter table | |
* Show post cunter and use | |
* show more view post as popular | |
*/ | |
//Create function for new table for post counter | |
function wpb_set_post_views($postID) { | |
$count_key = 'wpb_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); | |
//user this function for action | |
function wpb_track_post_views ($post_id) { | |
if ( !is_single() ) return; | |
if ( empty ( $post_id) ) { | |
global $post; | |
$post_id = $post->ID; | |
} | |
wpb_set_post_views($post_id); | |
} | |
add_action( 'wp_head', 'wpb_track_post_views'); |
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
/** | |
* use as post view count. add bellow code in functions.php file | |
*/ | |
function wpb_get_post_views($postID){ | |
$count_key = 'wpb_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; | |
} | |
// to use post cunter call the function in your post loop like below | |
<?php echo wpb_get_post_views(get_the_ID()); ?> | |
/** | |
* use as popular post by most view post use below post query | |
*/ | |
<?php | |
$popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_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