۲ قاریی
درست کردن post_view با استفاده از تابع
جامعه وردپرس (برنامه نویسی) ایجاد شده در ۰۷ آبان ۱۴۰۳
<?php 
// ثبت کردن بازدیدها
function dwt_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    dwt_set_post_views($post_id);
}
add_action( 'wp_head', 'dwt_track_post_views');
// تنظیم کردن و گرفتن بازدیدها
function dwt_set_post_views($post_id) {
    $count_key = '_dwt_post_views_count';
    $count = get_post_meta($post_id, $count_key, true);
    if($count==''){
        $count = 0;
        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);
    }
}
// نمایش تعداد بازدیدها
function dwt_get_post_views($post_id){
    $count_key = '_dwt_post_views_count';
    $count = get_post_meta($post_id, $count_key, true);
    if($count==''){
        delete_post_meta($post_id, $count_key);
        add_post_meta($post_id, $count_key, '0');
        return "0";
    }
    return $count;
}

سلام بسیار عالی بود

فقط چندتا نکته میگم که کارتون رو حرفه‌ای‌تر کنه

سعی کنید از ternary operator استفاده کنید که از تکرار بعضی از خطوط و if else جلوگیری بشه مثلا

$count = get_post_meta($post_id, $count_key, true);
$count = empty($count) ? 0 : $count;
update_post_meta($post_id, $count_key, $count + 1);

 

ابوالفضل محجوب ۰۸ آبان ۱۴۰۳، ۰۵:۱۱

سلام و احترام
کدتون رو کمی ریفکتور کردم
مرسی از مشارکت شما

 

function dwt_track_post_views($post_id) {
    if (!is_single() || is_admin()) return;
    if (empty($post_id)) {
        global $post;
        $post_id = isset($post->ID) ? $post->ID : null;
    }
    if ($post_id) {
        dwt_set_post_views($post_id);
    }
}
add_action('wp_head', 'dwt_track_post_views');
// Set or increment post views
function dwt_set_post_views($post_id) {
    $count_key = '_dwt_post_views_count';
    $count = (int) get_post_meta($post_id, $count_key, true);
    if ($count === 0) {
        update_post_meta($post_id, $count_key, 1);
    } else {
        update_post_meta($post_id, $count_key, $count + 1);
    }
}
// Retrieve post view count
function dwt_get_post_views($post_id) {
    $count_key = '_dwt_post_views_count';
    $count = (int) get_post_meta($post_id, $count_key, true);
    if ($count === 0) {
        return "0";
    }
    return (string) $count;
}
بهنام مرادی ۰۸ آبان ۱۴۰۳، ۰۸:۵۶