Skip to content

Latest commit

Β 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Media Usage Tracker

A comprehensive WordPress plugin that tracks where images and media files are used across your website, including posts, pages, Gutenberg blocks, and frontend HTML/CSS. Never lose track of your media files again!

πŸš€ Features

  • πŸ” Comprehensive Tracking: Monitors image usage in post content, metadata, Gutenberg blocks, and frontend HTML/CSS
  • ⚑ Real-time Updates: Automatically scans content when posts are saved
  • πŸ“… Scheduled Scanning: Configurable cron jobs for regular site-wide scans
  • πŸ“š Media Library Integration: Shows usage information directly in the media details page
  • πŸš€ Performance Optimized: Built-in caching system and batch processing
  • βš™οΈ Admin Dashboard: Complete settings page with usage statistics and manual controls
  • 🧹 Automatic Cleanup: Removes tracking data when posts or media are deleted
  • πŸ’» WP-CLI Support: Command-line interface for automation and server management
  • 🎯 Gutenberg Support: Full support for modern Gutenberg image and gallery blocks

πŸ“‹ Requirements

  • WordPress 5.0 or higher
  • PHP 7.4 or higher
  • MySQL 5.6 or higher
  • WP-CLI (optional, for command-line features)

πŸ”§ Installation

Method 1: Manual Installation

  1. Download the plugin files
  2. Upload the entire media-usage-tracker folder to /wp-content/plugins/
  3. Activate the plugin through the 'Plugins' screen in WordPress
  4. Navigate to Settings > Media Usage Tracker to configure

Method 2: WordPress Admin

  1. Go to Plugins > Add New in your WordPress admin
  2. Upload the plugin ZIP file
  3. Click Install Now and then Activate
  4. Navigate to Settings > Media Usage Tracker to configure

Initial Setup

After activation, the plugin will:

  • Create the necessary database table
  • Schedule automatic scans
  • Run an initial scan of your content (may take a few minutes for large sites)

🎯 How to Use

Viewing Media Usage

In Media Library

  1. Go to Media > Library
  2. Click on any image to open the details panel
  3. Scroll down to see the "Usage Locations" section
  4. Click "Refresh" to update usage data in real-time
  5. Click on any usage location to open that post/page for editing

Usage Information Includes:

  • Post Content: Images in post/page content, Gutenberg blocks
  • Post Metadata: Featured images, custom fields
  • Frontend HTML: Images found in rendered pages
  • Attachment Metadata: Parent post relationships

Admin Settings

Navigate to Settings > Media Usage Tracker to configure:

Scanning Settings

  • Enable Frontend Scanning: Scan rendered HTML/CSS for image usage
  • Enable Metadata Scanning: Scan post content and metadata
  • Scan Frequency: How often automatic scans run (hourly, daily, weekly)
  • Cache Duration: How long to cache usage data (in minutes)
  • Batch Size: Number of items processed per scan batch
  • Cleanup Days: Remove inactive records after X days

Manual Operations

  • Scan Now: Trigger an immediate scan of all content
  • Clear Cache: Remove all cached usage data
  • Clean Up Orphaned Records: Remove tracking data for deleted content

Usage Statistics

The admin page displays:

  • Total usage records by type
  • Last scan timestamps
  • Next scheduled scan times
  • Database statistics
  • Scanning status

πŸ’» WP-CLI Commands

The plugin includes comprehensive WP-CLI support for automation and server management:

Scanning Commands

# Scan all posts for media usage
wp media-usage scan

# Force rescan all posts (ignore timestamps)
wp media-usage scan --force

# Scan specific post type with custom batch size
wp media-usage scan --post-type=post --batch-size=100

# Scan frontend pages for media usage
wp media-usage scan_frontend --batch-size=20

Cleanup Commands

# Clean up orphaned usage records
wp media-usage cleanup

# Preview cleanup without making changes
wp media-usage cleanup --dry-run

# Clean up old inactive records (default: 30 days)
wp media-usage cleanup_old

# Clean up records older than 60 days
wp media-usage cleanup_old --days=60

# Preview old records cleanup
wp media-usage cleanup_old --dry-run

Information Commands

# Show usage statistics
wp media-usage stats

# Show statistics in JSON format
wp media-usage stats --format=json

# Show scan status and schedule information
wp media-usage status

Utility Commands

# Reset all data and rescan everything
wp media-usage reset

# Reset without confirmation prompt
wp media-usage reset --yes

πŸ”§ Advanced Configuration

Hooks and Filters

Actions

// Fired after post content scan
add_action('mut_post_scan_completed', 'my_post_scan_callback');

// Fired after frontend scan
add_action('mut_frontend_scan_completed', 'my_frontend_scan_callback');

// Fired after data cleanup
add_action('mut_cleanup_completed', 'my_cleanup_callback');

// Fired when post is deleted
add_action('mut_post_deleted', 'my_post_deleted_callback');

// Fired when attachment is deleted
add_action('mut_attachment_deleted', 'my_attachment_deleted_callback');

Filters

// Modify which post types are scanned
add_filter('mut_scan_post_types', function($post_types) {
    $post_types[] = 'custom_post_type';
    return $post_types;
});

// Add custom meta fields to scan
add_filter('mut_meta_fields_to_scan', function($fields) {
    $fields[] = 'custom_image_field';
    return $fields;
});

// Override cache duration per usage type
add_filter('mut_cache_duration', function($duration, $usage_type) {
    if ($usage_type === 'frontend_html') {
        return 120; // 2 hours for frontend scans
    }
    return $duration;
}, 10, 2);

Database Schema

The plugin creates a custom table wp_media_usage_tracker:

Column Type Description
id bigint(20) Primary key
attachment_id bigint(20) ID of the media file
post_id bigint(20) ID of the post/page (NULL for site-wide)
post_type varchar(20) Type of post where media is used
usage_type varchar(50) Type of usage (post_content, post_meta, etc.)
usage_context varchar(255) Specific context (img_tag, gutenberg_image_block, etc.)
found_url text URL where the image was found
last_found datetime Timestamp of last detection
is_active tinyint(1) Whether the usage is currently active

Usage Types

  • post_content: Images in post/page content
  • post_meta: Featured images and custom fields
  • frontend_html: Images found in rendered HTML
  • attachment_meta: Parent post relationships

Usage Contexts

  • img_tag: Standard HTML img tags
  • gutenberg_image_block: Gutenberg image blocks
  • gutenberg_gallery_block: Gutenberg gallery blocks
  • gallery_shortcode: WordPress gallery shortcodes
  • css_background: CSS background images
  • featured_image: Post featured images
  • attached_to_post: Attachment parent relationships

πŸ” Scanning Methods

1. Post Content Scanning

  • HTML img tags: <img src="..." />
  • Gutenberg image blocks: <!-- wp:image {"id":123} -->
  • Gutenberg gallery blocks: <!-- wp:gallery {"ids":[1,2,3]} -->
  • Legacy gallery shortcodes: [gallery ids="1,2,3"]

2. Metadata Scanning

  • Featured images: _thumbnail_id meta field
  • Custom fields: Any meta field containing image URLs or IDs
  • Theme-specific fields: Configurable via filters

3. Frontend Scanning

  • Rendered HTML: Scans actual page output for img tags
  • CSS backgrounds: background-image: url(...) properties
  • Dynamic content: Images loaded via JavaScript/AJAX

πŸš€ Performance Features

  • Transient Caching: Usage data cached for configurable duration
  • Batch Processing: Large datasets processed in manageable chunks
  • Selective Scanning: Only scan changed content when possible
  • Background Processing: Heavy operations run via WordPress cron
  • Automatic Cleanup: Removes orphaned data when content is deleted
  • Database Optimization: Indexed queries for fast lookups

πŸ› οΈ Troubleshooting

Common Issues

Scans Not Running

  1. Check if WordPress cron is working: wp cron event list
  2. Verify plugin settings are enabled
  3. Check server error logs for PHP errors
  4. Try running a manual scan via WP-CLI: wp media-usage scan

Missing Usage Data

  1. Run a manual scan: Settings > Media Usage Tracker > Scan Now
  2. Check if the content was modified recently
  3. Verify the image is actually embedded in the content
  4. Try force scanning: wp media-usage scan --force

Performance Issues

  1. Reduce batch size in settings
  2. Increase cache duration
  3. Disable frontend scanning if not needed
  4. Run scans during off-peak hours

Database Issues

  1. Check database table exists: wp db query "SHOW TABLES LIKE '%media_usage_tracker%'"
  2. Recreate table: Deactivate and reactivate plugin
  3. Clean up orphaned records: wp media-usage cleanup

Debug Mode

Enable WordPress debug mode to see detailed logging:

// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

Check /wp-content/debug.log for plugin messages starting with "MUT:".

Manual Database Cleanup

If needed, you can manually clean the database:

-- Remove all plugin data
DROP TABLE IF EXISTS wp_media_usage_tracker;
DELETE FROM wp_options WHERE option_name LIKE 'mut_%';
DELETE FROM wp_postmeta WHERE meta_key LIKE '_mut_%';

πŸ“Š Usage Examples

Finding Unused Images

# Get all attachments
wp post list --post_type=attachment --format=ids

# Check usage for specific attachment
wp db query "SELECT * FROM wp_media_usage_tracker WHERE attachment_id = 123"

# Find attachments with no usage records
wp db query "
SELECT p.ID, p.post_title 
FROM wp_posts p 
LEFT JOIN wp_media_usage_tracker mut ON p.ID = mut.attachment_id 
WHERE p.post_type = 'attachment' 
AND mut.attachment_id IS NULL
"

Bulk Operations

# Scan only posts (not pages)
wp media-usage scan --post-type=post

# Clean up old records older than 7 days
wp media-usage cleanup_old --days=7

# Get usage stats in JSON for external processing
wp media-usage stats --format=json > usage-stats.json

πŸ”„ Migration and Backup

Backup Usage Data

# Export usage data
wp db export --tables=wp_media_usage_tracker usage-backup.sql

# Export with specific conditions
wp db query "SELECT * FROM wp_media_usage_tracker WHERE is_active = 1" --format=csv > active-usage.csv

Restore Usage Data

# Import backup
wp db import usage-backup.sql

# Verify data
wp media-usage stats

πŸ†˜ Support

Getting Help

  1. Check this documentation for common solutions
  2. Enable debug logging to identify specific issues
  3. Use WP-CLI commands for detailed diagnostics
  4. Check WordPress and PHP error logs

Reporting Issues

When reporting issues, please include:

  • WordPress version
  • PHP version
  • Plugin version
  • Error messages from logs
  • Steps to reproduce the issue
  • Output from wp media-usage status

Feature Requests

We welcome feature requests! Please describe:

  • The use case or problem you're trying to solve
  • How you envision the feature working
  • Any specific requirements or constraints

πŸ“ Changelog

1.0.1

  • Enhanced Responsive Image Detection: Fixed issue where responsive images with dimension suffixes (e.g., -1024x683.png) weren't being recognized
  • Improved URL Resolution: Added smart detection for WordPress-generated image sizes by verifying against attachment metadata
  • Better Gutenberg Block Support: Enhanced scanning for complex Gutenberg blocks with embedded responsive images
  • Pattern Matching: Uses regex to detect size patterns while ensuring only legitimate WordPress sizes are processed

1.0.0

  • Initial release
  • Complete media usage tracking system
  • Admin interface and settings
  • Cron-based scanning
  • Media library integration
  • Gutenberg block support
  • Automatic cleanup on deletion
  • WP-CLI command support
  • Performance optimizations
  • Comprehensive documentation

πŸ“„ License

This plugin is licensed under the GPL v2 or later.

Media Usage Tracker
Copyright (C) 2025

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

Made with ❀️ for the WordPress community

About

WordPress plugin that tracks where images and media files are used across your website

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages