Created
December 24, 2018 00:36
-
-
Save pony012/212f79441cffb3ba02de177fab07ab0a to your computer and use it in GitHub Desktop.
This file contains 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 to display number of posts. | |
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 to 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); | |
} | |
} | |
// Add it to a column in WP-Admin | |
add_filter('manage_posts_columns', 'posts_column_views'); | |
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2); | |
function posts_column_views($defaults){ | |
$defaults['post_views'] = __('Views'); | |
return $defaults; | |
} | |
function posts_custom_column_views($column_name, $id){ | |
if($column_name === 'post_views'){ | |
echo getPostViews(get_the_ID()); | |
} | |
} | |
add_filter( 'manage_edit-post_sortable_columns', 'slug_views_sortable' ); | |
function slug_views_sortable( $cols ) { | |
$cols['post_views'] = 'post_views'; | |
return $cols; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment