شمارنده تعداد بازدید پستها بدون افزونه در وردپرس (Post View Counter)
با تابع زیر در اکشن `wp_head` بازدید ثبت شده و با `[post_views]` تعداد بازدیدها نمایش داده میشود.
<?php
/**
* سیستم سبک ثبت و نمایش تعداد بازدید پست در متای وردپرس
*/
function bisco_track_post_views() {
if ( ! is_single() ) {
return;
}
global $post;
if ( ! isset( $post->ID ) ) {
return;
}
// عدم شمارش بازدید رباتها یا پیشنمایشها
if ( is_preview() || is_robots() ) {
return;
}
$post_id = $post->ID;
$count_key = 'bisco_post_views_count';
$count = (int) get_post_meta( $post_id, $count_key, true );
if ( empty( $count ) ) {
delete_post_meta( $post_id, $count_key );
add_post_meta( $post_id, $count_key, 1 );
} else {
$count++;
update_post_meta( $post_id, $count_key, $count );
}
}
add_action( 'wp_head', 'bisco_track_post_views' );
// شورتکد نمایش بازدید
add_shortcode( 'post_views', function() {
$post_id = get_the_ID();
$count = (int) get_post_meta( $post_id, 'bisco_post_views_count', true );
return '<span class="bisco-post-views">بازدید: ' . number_format_i18n( $count ) . '</span>';
} );