page views



// Function to increment post/page views
function increment_views() {
    if (is_single() || is_page()) {
        $post_id = get_the_ID();
        $views = get_post_meta($post_id, 'views', true);
        $views = $views ? $views + 1 : 1;
        update_post_meta($post_id, 'views', $views);
    }
}
add_action('wp_head', 'increment_views');

// Display post/page views on single post/page for all users and visitors
function display_views($content) {
    if (is_single() || is_page()) {
        $post_id = get_the_ID();
        $views = get_post_meta($post_id, 'views', true);
        $views_html = '<div class="post-views">Views: 👀 ' . ($views ? $views : 0) . '</div>';

        // Append post/page views to the end of the content
        $content .= $views_html;

        // Also, add post/page views to the post meta
        add_post_meta($post_id, 'views_meta', $views, true);
    }

    return $content;
}
add_filter('the_content', 'display_views');

// Add post/page views column to admin dashboard
function add_views_column($columns) {
    $columns['views'] = 'Views';
    return $columns;
}
add_filter('manage_posts_columns', 'add_views_column');
add_filter('manage_pages_columns', 'add_views_column');

// Display post/page views count in the admin dashboard
function display_views_admin($column, $post_id) {
    if ($column === 'views') {
        $views = get_post_meta($post_id, 'views', true);
        echo $views ? $views : 0;
    }
}
add_action('manage_posts_custom_column', 'display_views_admin', 10, 2);
add_action('manage_pages_custom_column', 'display_views_admin', 10, 2);

1 thought on “page views”

Leave a Comment

Your email address will not be published. Required fields are marked *