Last active
December 2, 2023 18:42
-
-
Save softiconic/d98d5ca8212183344b491ab53342b687 to your computer and use it in GitHub Desktop.
Track WordPress post views without using a plugin.
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 gt_get_post_view() { | |
$count = get_post_meta( get_the_ID(), 'post_views_count', true ); | |
return "$count views"; | |
} | |
function gt_set_post_view() { | |
$key = 'post_views_count'; | |
$post_id = get_the_ID(); | |
$count = (int) get_post_meta( $post_id, $key, true ); | |
$count++; | |
update_post_meta( $post_id, $key, $count ); | |
} | |
function gt_posts_column_views( $columns ) { | |
$columns['post_views'] = 'Views'; | |
return $columns; | |
} | |
function gt_posts_custom_column_views( $column ) { | |
if ( $column === 'post_views') { | |
echo gt_get_post_view(); | |
} | |
} | |
add_filter( 'manage_posts_columns', 'gt_posts_column_views' ); | |
add_action( 'manage_posts_custom_column', 'gt_posts_custom_column_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
<?php gt_set_post_view(); ?> | |
<?= gt_get_post_view(); ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment