<?php


/**
 * this function records the number of views for the single post in database
 * @param type $postID
 */

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);

    }

}


//------------------------------------------------------------------------------

/**
 * this function fetchs the number of single post views to use it in the loop
 * @param type $postID
 * @return string
 */

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";

    }

    return $count . ' ';

}

//------------------------------------------------------------------------------

/**
 * Add it to a column in WP-Admin in normal posts
 */

add_filter('manage_courses_posts_columns', 'posts_column_views');

add_action('manage_courses_posts_custom_column', 'posts_custom_column_views', 5, 2);

function posts_column_views($defaults)
{

    $defaults['post_views'] = __('عدد المشاهدات');

    return $defaults;

}

/**
 *
 * @param type $column_name
 * @param type $id
 */

function posts_custom_column_views($column_name, $id)
{

    if ($column_name === 'post_views') {

        echo getPostViews(get_the_ID());

    }

}


