Enjoying these plugins? ☕ Buy me a coffee to support ongoing development.

Post Views Counter Lite

A lightweight, single-file WordPress plugin that tracks and displays view counts for posts with AJAX or PHP fallback increment, shortcode support, and bot/admin exclusion options.

Single File v1.0.0 Updated 1 month ago

YT Post Views Counter Lite

A lightweight, single-file WordPress plugin that tracks and displays view counts for posts with AJAX or PHP fallback increment, shortcode support, and bot/admin exclusion options.

Features

  • View Tracking: Accurate post view counting stored in post meta
  • Dual Tracking Methods: AJAX (cache-friendly) or PHP fallback
  • Bot Detection: Automatically excludes common bots and crawlers
  • Admin Exclusion: Option to exclude administrator views
  • Flexible Display: Show counts via shortcode, before/after content, or manually
  • Customizable Format: Configure display text with placeholder support
  • Multiple Post Types: Track views for posts, pages, or custom post types
  • Admin Integration: Sortable views column in posts list
  • Eye Icon: Optional CSS-based icon for visual appeal
  • Translation Ready: Full i18n/l10n support
  • WPCS Compliant: Follows WordPress Coding Standards
  • Secure: Proper sanitization, validation, nonce verification, and escaping

Files Structure

yt-post-views-counter-lite.php    # Main plugin file (~500 lines)
yt-post-views-counter-lite.js     # AJAX tracking script
yt-post-views-counter-lite.css    # Frontend styling
README.md                          # This documentation

Installation

  1. Upload the yt-post-views-counter-lite folder to /wp-content/plugins/ directory
  2. Activate the plugin through the 'Plugins' menu in WordPress
  3. Go to Settings > YT Post Views Counter to configure options
  4. Use the [post_views] shortcode anywhere to display view counts

Configuration

General Settings

  • Enable Tracking: Toggle view counting on/off
  • Tracking Method: Choose between AJAX (recommended) or PHP fallback
  • Post Types: Select which post types should have view tracking (Posts, Pages, etc.)

Exclusion Settings

  • Exclude Bots: Don't count views from common bots and crawlers
  • Exclude Administrators: Don't count views from logged-in administrators

Display Settings

  • Display Position:
    • None (Manual - use shortcode)
    • Before content
    • After content
  • Display Format: Customize text using {count} placeholder (e.g., {count} views, Viewed {count} times)
  • Display Icon: Show/hide the eye icon before the count

Usage

Shortcode

Display view count anywhere using the [post_views] shortcode:

// Basic usage (shows current post views)
[post_views]

// Show specific post views by ID
[post_views id="123"]

// Customize format for single use
[post_views format="{count} people viewed this"]

// Hide icon for single use
[post_views icon="false"]

// Combined attributes
[post_views id="456" format="Views: {count}" icon="false"]

Programmatic Access

// Get plugin instance
$yt_pvcl = YT_Post_Views_Counter_Lite::get_instance();

// Get view count for current post
$views = $yt_pvcl->get_post_views();

// Get view count for specific post
$views = $yt_pvcl->get_post_views( 123 );

// Display formatted view count
echo $yt_pvcl->render_shortcode( array( 'id' => get_the_ID() ) );

Template Integration

// In your theme template files
<?php
if ( class_exists( 'YT_Post_Views_Counter_Lite' ) ) {
    $yt_pvcl = YT_Post_Views_Counter_Lite::get_instance();
    echo '<div class="my-custom-views">';
    echo 'This post has been viewed ' . esc_html( $yt_pvcl->get_post_views() ) . ' times.';
    echo '</div>';
}
?>

Admin Views Column

The plugin automatically adds a "Views" column to your posts list in the WordPress admin. This column:

  • Shows the view count for each post
  • Is sortable (click to sort by most/least viewed)
  • Updates in real-time as views are tracked

How It Works

AJAX Tracking (Recommended)

  1. When a visitor views a post, JavaScript loads
  2. An AJAX request is sent to WordPress
  3. Server validates the request (nonce, bot detection, admin check)
  4. View count increments in post meta
  5. Response sent back (optional count update)

Benefits: Cache-friendly, works with caching plugins, doesn't affect page load time

PHP Fallback Tracking

  1. When a visitor views a post, PHP executes during page load
  2. Server checks if visitor should be counted
  3. View count increments directly in post meta

Benefits: Works without JavaScript, simpler implementation

Bot Detection

The plugin detects common bots using user agent string matching:

  • Google Bot, Bing Bot, Yahoo Slurp
  • Facebook External Hit
  • Various crawlers and spiders
  • Media partners and preview bots

Data Storage

View counts are stored as post meta with key _yt_pvcl_post_views:

  • Integer value
  • Updated atomically
  • Queryable and sortable
  • Removed on plugin uninstall

Customization

Custom CSS Styling

Override default styles in your theme:

/* Change text color */
.yt-pvcl-post-views {
    color: #your-color;
}

/* Modify icon */
.yt-pvcl-icon::before {
    border-color: #your-color;
}

/* Change font size */
.yt-pvcl-post-views {
    font-size: 1em;
}

/* Remove icon entirely */
.yt-pvcl-icon {
    display: none;
}

Custom Display Format

In plugin settings, use these format examples:

  • {count} views (default)
  • Viewed {count} times
  • {count} (number only)
  • 👁️ {count}
  • {count} reads

Advanced Usage

Most Viewed Posts Query

// Get 5 most viewed posts
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => 5,
    'meta_key'       => '_yt_pvcl_post_views',
    'orderby'        => 'meta_value_num',
    'order'          => 'DESC',
);

$popular_posts = new WP_Query( $args );

if ( $popular_posts->have_posts() ) {
    echo '<h3>Most Popular Posts</h3><ul>';
    while ( $popular_posts->have_posts() ) {
        $popular_posts->the_post();
        $views = get_post_meta( get_the_ID(), '_yt_pvcl_post_views', true );
        echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a> (' . $views . ' views)</li>';
    }
    echo '</ul>';
    wp_reset_postdata();
}

Reset View Counts

// Reset views for a specific post
delete_post_meta( $post_id, '_yt_pvcl_post_views' );

// Reset all view counts (use with caution!)
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->postmeta} WHERE meta_key = '_yt_pvcl_post_views'" );

Export View Statistics

// Get all posts with view counts
global $wpdb;
$results = $wpdb->get_results(
    "SELECT post_id, meta_value as views
     FROM {$wpdb->postmeta}
     WHERE meta_key = '_yt_pvcl_post_views'
     ORDER BY CAST(meta_value AS UNSIGNED) DESC"
);

foreach ( $results as $row ) {
    echo "Post ID: {$row->post_id} - Views: {$row->views}n";
}

Troubleshooting

Views Not Counting

  1. Check if tracking is enabled: Settings > YT Post Views Counter > Enable Tracking
  2. Verify post type: Make sure the post type is selected in settings
  3. Admin exclusion: Disable "Exclude Administrators" if testing while logged in
  4. JavaScript errors: Check browser console for errors (AJAX mode)
  5. Caching: Clear site cache after activating plugin

AJAX Not Working

  1. Switch to PHP fallback: Change tracking method in settings
  2. Check JavaScript console: Look for error messages
  3. Verify jQuery: Ensure theme loads jQuery properly
  4. Plugin conflicts: Temporarily disable other plugins to test

Display Issues

  1. Check display position: Ensure it's not set to "None" if auto-display is expected
  2. Theme compatibility: Some themes may override styles
  3. Use shortcode: Try [post_views] to verify counts are tracking
  4. Inspect CSS: Check if theme styles are conflicting

Performance Concerns

  1. Use AJAX method: More cache-friendly than PHP
  2. Enable bot exclusion: Reduces unnecessary counting
  3. Limit post types: Only track what you need
  4. Database optimization: View counts use indexed post meta

Security

The plugin implements WordPress security best practices:

  • ✅ Direct file access prevention
  • ✅ Nonce verification for AJAX requests
  • ✅ Capability checks for admin functions
  • ✅ Input sanitization (sanitize_text_field, absint)
  • ✅ Output escaping (esc_html, esc_attr, esc_url)
  • ✅ Prepared SQL statements ($wpdb->prepare)
  • ✅ CSRF protection
  • ✅ XSS prevention

Performance

  • Lightweight: ~500 lines of PHP, minimal JavaScript
  • Efficient queries: Uses indexed post meta
  • Cache-friendly: AJAX method works with caching plugins
  • No external dependencies: Pure WordPress implementation
  • Minimal overhead: Single meta query per post view

Browser Compatibility

  • Chrome/Edge (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • IE11+ (AJAX mode requires polyfills)

WordPress Compatibility

  • Minimum WordPress version: 5.8
  • Tested up to: 6.7
  • Minimum PHP version: 7.4
  • Recommended PHP version: 8.0+

Multisite Compatibility

The plugin is multisite-compatible:

  • Network activate to enable on all sites
  • Or activate individually per site
  • View counts are site-specific

Uninstallation

When you delete the plugin:

  1. All plugin options are removed from the database
  2. All post view counts (post meta) are removed
  3. No trace of the plugin remains

To preserve view counts, deactivate instead of deleting.

Code Quality

  • WPCS Compliant: Follows WordPress Coding Standards
  • Documented: Inline PHPDoc comments throughout
  • Secure: Security best practices implemented
  • Maintainable: Clean, modular code structure
  • Tested: Activation, deactivation, and uninstall hooks tested

Line Count

  • Main PHP file: ~500 lines (including comments and documentation)
  • JavaScript: ~50 lines
  • CSS: ~100 lines

Development

Running PHPCS

phpcs --standard=WordPress yt-post-views-counter-lite.php

Testing Checklist

  • [ ] Plugin activates without errors
  • [ ] Settings page displays correctly
  • [ ] Settings save properly
  • [ ] AJAX tracking works
  • [ ] PHP fallback works
  • [ ] Shortcode renders correctly
  • [ ] Bot detection works
  • [ ] Admin exclusion works
  • [ ] Admin column displays and sorts
  • [ ] Frontend display works (before/after)
  • [ ] Plugin deactivates cleanly
  • [ ] Plugin uninstalls and removes all data
  • [ ] No PHP warnings or notices
  • [ ] No JavaScript console errors
  • [ ] Works with popular caching plugins

Support

For issues, questions, or feature requests:

  1. Check the troubleshooting section above
  2. Review WordPress Plugin Handbook: https://developer.wordpress.org/plugins/
  3. Check WordPress Coding Standards: https://developer.wordpress.org/coding-standards/

Changelog

Version 1.0.0

  • Initial release
  • AJAX and PHP tracking methods
  • Bot and admin exclusion
  • Shortcode support
  • Admin column with sorting
  • Customizable display options
  • Translation ready
  • WPCS compliant

Credits

Built following WordPress Plugin Handbook and WPCS guidelines using the YT Plugin Boilerplate.

License

GPL v2 or later - https://www.gnu.org/licenses/gpl-2.0.html

Author

Krasen Slavov - https://krasenslavov.com

Privacy

This plugin:

  • Does NOT collect personal data
  • Does NOT use cookies
  • Does NOT send data to external servers
  • Only stores anonymous view counts in your WordPress database
  • Is GDPR-friendly

Future Enhancements (Potential)

  • Dashboard widget with view statistics
  • Custom date range filtering
  • Export views to CSV
  • Most popular posts widget
  • View count reset functionality
  • Per-user view history (optional)
  • Integration with popular analytics plugins
  • REST API endpoints

Note: This is a "Lite" version focused on core functionality. The plugin is designed to be simple, performant, and lightweight while providing essential view tracking features.