Menu

WP Optimal State Plugin

wp optimal state - wordpress plugin

Version 1.0.2
Last Updated: October 2025
Price: FREE ✅

💾 DOWNLOAD HERE 💾


Table of Contents


Introduction

What is WP Optimal State?

WP Optimal State is a comprehensive database optimization and maintenance plugin designed to keep your WordPress website running at peak performance. Over time, WordPress databases accumulate unnecessary data such as post revisions, spam comments, orphaned metadata, and expired transients. This bloat can slow down your site and increase hosting costs.

WP Optimal State provides an intuitive interface to safely identify, review, and remove this unnecessary data while optimizing your database tables for maximum efficiency.

Key Benefits

  • Improved Performance: Reduce database size and query times
  • Better User Experience: Faster page loads and admin operations
  • Cost Savings: Smaller databases mean lower hosting costs
  • Easy Maintenance: One-click optimization for routine cleaning
  • Full Control: Choose exactly what to clean and when
  • Safe Operations: Clear warnings for potentially destructive actions

Who Should Use This Plugin?

  • Website Owners: Keep your site fast and efficient
  • Developers: Maintain clean development and staging environments
  • Agencies: Regular maintenance for client websites
  • Bloggers: Manage post revisions and comment spam
  • E-commerce Sites: Optimize product databases and transients

Installation

Automatic Installation

  1. Log in to your WordPress admin dashboard
  2. Navigate to Plugins → Add New
  3. Search for “WP Optimal State”
  4. Click Install Now next to the plugin
  5. Click Activate when installation completes

Manual Installation

  1. Download the plugin ZIP file
  2. Log in to your WordPress admin dashboard
  3. Navigate to Plugins → Add New
  4. Click Upload Plugin at the top
  5. Click Choose File and select the ZIP file
  6. Click Install Now
  7. Click Activate Plugin when installation completes

Installation via FTP

  1. Download and extract the plugin ZIP file
  2. Upload the wp-optimal-state folder to /wp-content/plugins/
  3. Log in to your WordPress admin dashboard
  4. Navigate to Plugins
  5. Find “WP Optimal State” and click Activate

System Requirements

  • WordPress: 5.0 or higher
  • PHP: 7.0 or higher
  • MySQL: 5.6 or higher (or MariaDB 10.0+)
  • User Permission: Administrator access required

Getting Started

First-Time Setup

Step 1: Access the Plugin

After activation, you’ll find Optimal State in your WordPress admin menu with a performance icon (⚡).

Click on Optimal State to access the main dashboard.

Step 2: Create a Database Backup

⚠️ CRITICAL STEP – DO NOT SKIP!

Before using any cleanup features:

  1. Navigate to Tools → Export in WordPress
  2. Select “All content” and click Download Export File
  3. Save the export file to a safe location

Additional Backup Methods:

  • Use your hosting control panel’s backup feature
  • Use a dedicated backup plugin (UpdraftPlus, BackupBuddy, etc.)
  • Use phpMyAdmin to export your database
  • Contact your hosting provider for backup assistance

Step 3: Review Statistics

The plugin will automatically scan your database and display statistics about:

  • Post revisions count
  • Auto drafts
  • Trashed items
  • Spam comments
  • Orphaned metadata
  • Transients
  • Database size

Take a moment to review these numbers to understand your database health.

Step 4: Start with Safe Operations

For your first cleanup, we recommend using the One-Click Optimization feature, which only performs safe operations that won’t affect your published content.


Dashboard Overview

Main Interface Sections

1. One-Click Optimization Panel (Top Left)

Purple gradient card with rocket icon 🚀

This is your quick-access optimization tool that performs all safe cleanup operations simultaneously:

  • Removes post revisions
  • Deletes auto drafts
  • Cleans spam comments
  • Removes trashed comments
  • Cleans orphaned post metadata
  • Removes orphaned comment metadata
  • Deletes orphaned relationships
  • Clears expired transients
  • Removes orphaned user metadata
  • Deletes pingbacks
  • Removes trackbacks
  • Optimizes all database tables

When to Use:

  • Weekly maintenance
  • After major content updates
  • When site feels sluggish
  • Before important events or promotions

2. Database Statistics Panel (Top Right)

White card with chart icon 📊

Displays real-time statistics about your database:

  • Post Revisions: Number of old post versions
  • Auto Drafts: Automatically saved draft posts
  • Trashed Posts: Posts in trash (not permanently deleted)
  • Spam Comments: Comments marked as spam
  • Trashed Comments: Comments in trash
  • Orphaned Post Meta: Metadata for deleted posts
  • Orphaned Comment Meta: Metadata for deleted comments
  • Expired Transients: Outdated temporary data
  • All Transients: Total cached temporary data
  • Autoloaded Options: Number of auto-loading options
  • Autoload Size: Total size of autoloaded data
  • Total Database Size: Overall database size in MB/GB

Refresh Stats Button: Click to manually update statistics

3. Database Cleanup Section

Grid of individual cleanup items 🧹

Each cleanup item shows:

  • Title: Type of data (e.g., “Post Revisions”)
  • Count: Number of items found (badge)
  • Description: What this data type is
  • Warning Icon ⚠️: Appears for potentially destructive operations
  • Clean Now Button: Initiates cleanup for that specific item

Items are color-coded:

  • Gray background: Standard cleanup item
  • Red button: Cleanup action
  • Green button: Completed action (temporary)
  • Badge: Shows item count

4. Database Optimization Section

Tools for table-level optimization 🗄️

Two main functions:

Optimize All Tables

  • Repairs and optimizes all database tables
  • Reclaims unused space
  • Updates index statistics
  • Safe for all sites

Optimize Autoloaded Options

  • Finds large autoloaded options (>100KB)
  • Converts them to load on-demand
  • Excludes critical options (active_plugins, cron, rewrite_rules)
  • Reduces memory usage

5. Settings Section

Configuration options ⚙️

Delete Revisions Older Than

  • Set number of days (0-365)
  • 0 = disabled (keeps all revisions)
  • Default: 30 days
  • Recommended: 30-90 days depending on content update frequency

Clean Old Revisions Now Button

  • Immediately removes revisions older than specified days
  • Separate from other cleanup operations
  • Useful for one-time bulk cleanup

Features & Functions

One-Click Optimization

Purpose: Perform all safe database maintenance in one action

What It Does:

  1. Removes all post revisions
  2. Deletes auto-draft posts
  3. Cleans spam comments
  4. Removes trashed comments
  5. Deletes orphaned post metadata
  6. Removes orphaned comment metadata
  7. Cleans orphaned term relationships
  8. Deletes expired transients
  9. Removes orphaned user metadata
  10. Deletes pingbacks and trackbacks
  11. Optimizes all database tables

Process:

  1. Click the “Optimize Now” button
  2. Wait for processing (5-60 seconds depending on database size)
  3. Review results showing items cleaned
  4. Statistics automatically refresh

Safety Level: Safe – No published content affected

Recommended Frequency: Weekly or bi-weekly


Individual Cleanup Operations

Post Revisions

What It Is: WordPress automatically saves versions of your posts and pages every time you edit them.

Why Clean: Each revision is stored as a separate post in the database, potentially creating hundreds or thousands of entries.

Safety Level: Safe – You can still undo changes using remaining revisions

When to Clean:

  • Before major database operations
  • When revisions exceed 1000
  • If you don’t use the revision feature

Impact: Can reduce database size by 10-30% on content-heavy sites

Auto Drafts

What It Is: WordPress automatically saves draft posts as you type.

Why Clean: Abandoned posts remain as auto-drafts indefinitely.

Safety Level: Safe – Only removes abandoned drafts

When to Clean: Monthly or when count exceeds 50

Impact: Minimal database size reduction but improves post list clarity

Trashed Posts

What It Is: Posts moved to trash but not permanently deleted.

Why Clean: Trash doesn’t empty automatically.

Safety Level: ⚠️ CAUTION – Permanently deletes posts

When to Clean:

  • After reviewing trash contents
  • When certain items should be permanently removed
  • During major site cleanup

Impact: Varies based on trash contents

⚠️ Warning: This action cannot be undone. Review trash contents first via Posts → All Posts → Trash.

Spam Comments

What It Is: Comments marked as spam by Akismet or manual moderation.

Why Clean: Spam accumulates quickly on popular sites.

Safety Level: Safe – Legitimate comments not affected

When to Clean: Weekly or when spam count exceeds 100

Impact: Can significantly reduce comment table size on spam-heavy sites

Trashed Comments

What It Is: Comments moved to trash but not permanently deleted.

Why Clean: Trash doesn’t empty automatically.

Safety Level: Safe – Only deletes trashed comments

When to Clean: Monthly or when count is high

Impact: Moderate database size reduction

Orphaned Post Meta

What It Is: Custom fields and metadata attached to deleted posts.

Why Clean: When posts are deleted, their metadata often remains.

Safety Level: Safe – Only affects deleted post metadata

When to Clean: After bulk post deletions or monthly maintenance

Impact: Can reduce postmeta table size by 5-15%

Orphaned Comment Meta

What It Is: Metadata attached to deleted comments.

Why Clean: Reduces commentmeta table bloat.

Safety Level: Safe – Only affects deleted comment metadata

When to Clean: After comment cleanup or monthly

Impact: Minor database size reduction

Orphaned Relationships

What It Is: Term relationships (tags, categories) for deleted posts.

Why Clean: Keeps taxonomy tables clean.

Safety Level: Safe – Only removes relationships for deleted posts

When to Clean: After bulk deletions or quarterly

Impact: Minor database size reduction

Expired Transients

What It Is: Temporary cached data that has exceeded its expiration time.

Why Clean: WordPress doesn’t always clean these automatically.

Safety Level: Safe – Only removes expired cache

When to Clean:

  • Weekly as preventive maintenance
  • When options table is large
  • After deactivating plugins

Impact: Can significantly reduce options table size (5-25%)

All Transients

What It Is: All temporary cached data, expired and active.

Why Clean: Forces fresh data generation.

Safety Level: ⚠️ CAUTION – May temporarily slow site while cache rebuilds

When to Clean:

  • When troubleshooting caching issues
  • After major plugin updates
  • When site displays cached errors

Impact: Temporarily increases page generation time

⚠️ Warning: Site may be slower for 1-2 hours while cache rebuilds.

Duplicate Post Meta

What It Is: Duplicate entries in the postmeta table.

Why Clean: Database errors or plugin bugs can create duplicates.

Safety Level: Safe – Removes duplicates, keeps one copy

When to Clean:

  • After identifying duplicate issues
  • During annual deep cleanup
  • When postmeta table is unusually large

Impact: Varies depending on duplicate count

Duplicate Comment Meta

What It Is: Duplicate entries in the commentmeta table.

Why Clean: Prevents data inconsistencies.

Safety Level: Safe – Removes duplicates, keeps one copy

When to Clean: During thorough database maintenance

Impact: Minor database size reduction

Orphaned User Meta

What It Is: Metadata attached to deleted user accounts.

Why Clean: Keeps usermeta table clean.

Safety Level: Safe – Only affects deleted users

When to Clean:

  • After removing spam users
  • After bulk user deletions
  • Quarterly maintenance

Impact: Depends on user deletion history

Unapproved Comments

What It Is: Comments awaiting moderation approval.

Why Clean: Removes backlog of pending comments.

Safety Level: ⚠️ CAUTION – Deletes comments that might be legitimate

When to Clean:

  • When moderation queue is overwhelming
  • When closing comments on old posts
  • After reviewing pending comments

Impact: Varies based on comment volume

⚠️ Warning: Review pending comments first via Comments → Pending.

Pingbacks

What It Is: Notifications when other sites link to your content.

Why Clean: Many pingbacks are spam or from defunct sites.

Safety Level: Safe – Won’t affect regular comments

When to Clean:

  • If you don’t use pingbacks
  • When pingback spam is high
  • During comment cleanup

Impact: Reduces comment table size

Trackbacks

What It Is: Similar to pingbacks but using older protocol.

Why Clean: Rarely used in modern WordPress.

Safety Level: Safe – Won’t affect regular comments

When to Clean: Anytime, especially if not using trackbacks

Impact: Minor database size reduction


Database Table Optimization

Optimize All Tables

What It Does:

  • Runs MySQL OPTIMIZE TABLE command on all tables
  • Reclaims unused space from deleted rows
  • Defragments tables for better performance
  • Updates index statistics
  • Repairs minor table corruption

Technical Process:

OPTIMIZE TABLE wp_posts;
OPTIMIZE TABLE wp_postmeta;
OPTIMIZE TABLE wp_comments;
-- ... continues for all tables

When to Use:

  • After cleaning large amounts of data
  • Monthly maintenance
  • When database feels fragmented
  • After major content operations

Duration: 10 seconds to 5 minutes depending on database size

Safety Level: Safe – Non-destructive operation

Expected Results:

  • Slightly smaller database size
  • Improved query performance
  • Better index efficiency

Note: Tables are locked briefly during optimization, causing momentary slowdowns.

Optimize Autoloaded Options

What It Does:

  • Identifies options larger than 100KB set to autoload
  • Changes large options to load on-demand
  • Excludes critical options (active_plugins, cron, rewrite_rules)
  • Reduces memory usage on every page load

Why It Matters: Autoloaded options are loaded into memory on every single page request. Large autoloaded options can:

  • Increase memory usage
  • Slow down every page load
  • Cause timeout errors on shared hosting
  • Waste server resources

What’s Considered Large:

  • Options over 100KB (102,400 bytes)
  • Usually serialized arrays or cached data
  • Often created by poorly coded plugins

When to Use:

  • When autoload size exceeds 1MB
  • After deactivating plugins
  • When experiencing memory issues
  • During performance optimization

Safety Level: Safe – Critical options are protected

Expected Results:

  • Faster page loads (50-200ms improvement)
  • Reduced memory usage
  • More responsive admin panel

Settings Configuration

Revision Age Limit

Purpose: Automatically clean revisions older than X days

Configuration:

  • Field: Number input (0-365 days)
  • Default: 30 days
  • Disabled: Set to 0

Recommended Settings by Site Type:

Site Type Recommended Days Reason
Blog 30-60 Frequent content updates
Business 60-90 Moderate updates
E-commerce 14-30 Frequent product changes
Portfolio 90-180 Infrequent updates
News 14-30 Daily updates

How to Use:

  1. Enter number of days in the field
  2. Click “Clean Old Revisions Now” to apply immediately
  3. Or wait for scheduled cleanup (if configured)

Example: Setting “30 days” means:

  • Revisions from last 30 days are kept
  • Revisions older than 30 days are deleted
  • Protects recent editing history

Safety Guidelines

Before You Start

Essential Pre-Cleanup Steps

  1. Create Full Database Backup
    • Use WordPress Export (Tools → Export)
    • Use hosting control panel backup
    • Use backup plugin
    • Download backup to local computer
  2. Test on Staging Site First (Recommended)
    • Clone your site to staging environment
    • Run cleanup operations
    • Verify everything works correctly
    • Then apply to production
  3. Review Current Statistics
    • Check what will be cleaned
    • Verify counts make sense
    • Look for unexpectedly high numbers
  4. Schedule Maintenance Window
    • Choose low-traffic time
    • Inform team members
    • Allow 30-60 minutes
    • Have backup plan ready
  5. Document Current State
    • Take screenshots of statistics
    • Note database size before cleanup
    • Record page load times
    • Save list of active plugins

Understanding Risk Levels

Safe Operations (Green Light)

These operations only remove data that’s no longer needed or already deleted:

  • Post revisions
  • Auto drafts
  • Spam comments
  • Trashed comments
  • Orphaned metadata (all types)
  • Expired transients
  • Pingbacks
  • Trackbacks
  • Duplicate metadata
  • Database table optimization

Can be performed anytime with minimal risk

⚠️ Caution Required (Yellow Light)

These operations can affect visible content or site functionality:

  • Trashed Posts: Permanently deletes posts from trash
  • All Transients: Clears active cache (site may slow temporarily)
  • Unapproved Comments: Deletes pending comments

Review carefully before proceeding

🛑 High Risk Operations (Not Included)

WP Optimal State deliberately does NOT include:

  • Deleting published posts
  • Removing active comments
  • Modifying user accounts
  • Changing site settings
  • Affecting media files

These operations require manual action in WordPress

Recovery Procedures

If Something Goes Wrong

Immediate Steps:

  1. Don’t Panic
    • Most operations can be recovered from backup
    • Document what happened
    • Note error messages
  2. Restore from BackupMethod 1: WordPress Import
    • Go to Tools → Import
    • Install WordPress Importer
    • Upload your export XML file
    • Import content

    Method 2: Database Restore

    • Access phpMyAdmin
    • Select your database
    • Click Import tab
    • Upload backup SQL file
    • Execute import

    Method 3: Hosting Control Panel

    • Access cPanel or hosting dashboard
    • Find backup/restore section
    • Select database backup
    • Restore to original state
  3. Verify Site Functionality
    • Check homepage loads
    • Test admin access
    • Verify posts display
    • Test comments
    • Check contact forms
  4. Contact Support
    • Plugin support forum
    • Hosting provider
    • WordPress developer

Best Practices for Safe Operation

Daily Operations

  • Monitor database statistics
  • Check for unusual patterns
  • Keep regular backups

Weekly Operations

  • Run One-Click Optimization
  • Clean spam comments
  • Remove expired transients

Monthly Operations

  • Full database cleanup
  • Optimize autoloaded options
  • Review and clean old revisions
  • Optimize all tables

Quarterly Operations

  • Deep database analysis
  • Clean orphaned relationships
  • Review settings and schedules
  • Test restoration procedures

Troubleshooting

Common Issues and Solutions

Issue: “Unauthorized” Error Message

Symptoms:

  • Error message when clicking any button
  • AJAX operations fail
  • Statistics don’t load

Causes:

  • User lacks administrator permissions
  • Session expired
  • Nonce verification failed

Solutions:

  1. Log out and log back in
  2. Verify you have administrator role
  3. Check for conflicting security plugins
  4. Clear browser cookies
  5. Try different browser

Issue: Statistics Not Loading

Symptoms:

  • “Loading statistics…” message doesn’t disappear
  • Empty statistics panel
  • Spinning loader indefinitely

Causes:

  • Large database taking time to query
  • JavaScript conflict
  • Server timeout
  • Database connection issue

Solutions:

  1. Wait 60 seconds (large databases take time)
  2. Click “Refresh Stats” button
  3. Check browser console for JavaScript errors (F12)
  4. Disable other plugins temporarily
  5. Contact hosting about database performance
  6. Increase PHP max_execution_time

Issue: Operation Times Out

Symptoms:

  • White screen during cleanup
  • “Maximum execution time exceeded” error
  • Operation never completes

Causes:

  • Very large dataset to clean
  • Server resource limits
  • PHP timeout settings too low

Solutions:

  1. Clean smaller batches manually
  2. Increase PHP timeout (ask hosting provider)
  3. Use SSH/WP-CLI for large operations
  4. Schedule cleanups during off-peak hours
  5. Upgrade hosting plan

Technical Fix (for developers): Add to wp-config.php:

set_time_limit(300); // 5 minutes
ini_set('max_execution_time', 300);

Issue: Database Size Doesn’t Decrease

Symptoms:

  • Cleanup successful but database size unchanged
  • “Optimized X items” but no size reduction
  • Statistics show 0 items but database still large

Causes:

  • Database hasn’t reclaimed space yet
  • InnoDB storage engine doesn’t immediately release space
  • Large tables not yet optimized

Solutions:

  1. Click “Optimize All Tables” button
  2. Wait 24 hours for MySQL to reclaim space
  3. Run OPTIMIZE TABLE manually via phpMyAdmin
  4. Check if other data exists (uploads, plugins)

Note: InnoDB tables may not shrink immediately. Space is reused internally but file size may not decrease.


Issue: Site Slower After Cleanup

Symptoms:

  • Pages load slower than before
  • Admin dashboard sluggish
  • Database queries taking longer

Causes:

  • Cleared active transients/cache
  • Removed useful cache data
  • Database optimization in progress

Solutions:

  1. Wait 1-2 hours for cache to rebuild
  2. Visit site pages to regenerate cache
  3. Clear browser cache
  4. Flush object cache (if using)
  5. Check server resources

Prevention: Don’t clean “All Transients” unless necessary


Issue: Can’t Access Admin After Cleanup

Symptoms:

  • Login page works but dashboard won’t load
  • White screen after login
  • Database error messages

Causes:

  • Critical option accidentally modified
  • Active plugins affected
  • Corrupted session data

Solutions:

  1. Restore from backup immediately
  2. Access via FTP and rename plugins folder
  3. Use database restore via phpMyAdmin
  4. Contact hosting provider for emergency restore
  5. Try wp-admin/options.php directly

Emergency Recovery:

// Add to wp-config.php temporarily
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

Check wp-content/debug.log for errors


Issue: “Clean Now” Button Does Nothing

Symptoms:

  • Clicking button has no effect
  • No loading state
  • No error message

Causes:

  • JavaScript not loaded
  • jQuery conflict
  • Browser blocking requests
  • Ad blocker interference

Solutions:

  1. Hard refresh page (Ctrl+F5 or Cmd+Shift+R)
  2. Check browser console for errors
  3. Disable ad blockers temporarily
  4. Try different browser
  5. Clear browser cache
  6. Check for JavaScript conflicts with other plugins

Issue: Some Items Won’t Clean

Symptoms:

  • Cleanup reports 0 items deleted
  • Count remains same after cleaning
  • “Error – Try Again” message

Causes:

  • Database permissions issue
  • Corrupted table
  • Foreign key constraints
  • Protected items

Solutions:

  1. Check database user permissions
  2. Run database repair (wp-config.php: define(‘WP_ALLOW_REPAIR’, true))
  3. Access yoursite.com/wp-admin/maint/repair.php
  4. Review MySQL error logs
  5. Contact hosting provider

Error Messages Explained

Error Message Meaning Solution
“Unauthorized” User lacks permissions Log in as administrator
“Nonce verification failed” Security token expired Refresh page
“Cleanup failed” Database operation error Check error logs
“Maximum execution time” PHP timeout Increase time limits
“Out of memory” PHP memory exhausted Increase memory_limit
“Database connection lost” MySQL timeout Check database server
“Table doesn’t exist” Database corruption Run database repair

Debug Mode

Enable WordPress Debug Mode:

  1. Access site via FTP or hosting file manager
  2. Open wp-config.php
  3. Find: define('WP_DEBUG', false);
  4. Change to: define('WP_DEBUG', true);
  5. Add below it:
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
  1. Save file
  2. Reproduce issue
  3. Check wp-content/debug.log for errors
  4. Disable debug mode after troubleshooting

Important: Never leave debug mode enabled on live sites!


Best Practices

Maintenance Schedule

Weekly Maintenance (5-10 minutes)

Goal: Prevent database bloat

Tasks:

  • [ ] Run One-Click Optimization
  • [ ] Review database statistics
  • [ ] Check for unusual patterns
  • [ ] Verify site performance

Best Time: Sunday evening or Monday morning during low traffic


Monthly Maintenance (15-30 minutes)

Goal: Deep cleanup and optimization

Tasks:

  • [ ] Create fresh database backup
  • [ ] Run all safe cleanup operations individually
  • [ ] Clean old revisions (30+ days)
  • [ ] Optimize autoloaded options
  • [ ] Optimize all database tables
  • [ ] Review and document results
  • [ ] Compare database size to previous month

Best Time: First weekend of the month


Quarterly Maintenance (30-60 minutes)

Goal: Comprehensive database health check

Tasks:

  • [ ] Full database backup
  • [ ] Review all statistics carefully
  • [ ] Clean orphaned relationships
  • [ ] Review and clean duplicate metadata
  • [ ] Analyze slow query logs
  • [ ] Test database restoration
  • [ ] Update documentation
  • [ ] Review plugin settings
  • [ ] Consider permanent deletions (trashed items)

Best Time: End of business quarter


Performance Optimization Tips

Database-Level Optimization

  1. Keep Revisions Under Control
    • Limit revisions to 30-60 days
    • Or limit revision count: Add to wp-config.php:
    define('WP_POST_REVISIONS', 5);
    
  2. Regular Transient Cleanup
    • Clean expired transients weekly
    • Monitor transient growth
    • Identify plugins creating excessive transients
  3. Minimize Autoloaded Data
    • Keep autoload size under 1MB
    • Run autoload optimization monthly
    • Identify problematic plugins
  4. Optimize Tables Regularly
    • Run table optimization monthly
    • After large cleanup operations
    • When database feels fragmented
  5. Monitor Database Growth
    • Track database size monthly
    • Investigate sudden increases
    • Plan for scaling needs

WordPress-Level Optimization

  1. Use Object Caching
    • Install Redis or Memcached
    • Reduces database queries
    • Complements WP Optimal State
  2. Implement Page Caching
    • Use caching plugin (W3 Total Cache, WP Super Cache)
    • Reduces database load
    • Improves page speed
  3. Optimize Images
    • Use image optimization plugins
    • Reduces media library bloat
    • Improves load times
  4. Regular Plugin Audits
    • Remove unused plugins
    • Update regularly
    • Check for database-heavy plugins
  5. Use CDN
    • Offload static assets
    • Reduces server load
    • Improves global performance

Server-Level Optimization

  1. Adequate Resources
    • Sufficient RAM (min 1GB for WordPress)
    • SSD storage
    • Modern PHP version (7.4+)
  2. Database Server Tuning
    • Optimize MySQL/MariaDB configuration
    • Increase buffer sizes
    • Enable query cache (if available)
  3. PHP Configuration
    memory_limit = 256M
    max_execution_time = 300
    post_max_size = 64M
    upload_max_filesize = 64M
    
  4. Regular Server Maintenance
    • Update server software
    • Monitor resource usage
    • Check error logs

Security Best Practices

Protection Measures

  1. Always Backup First
    • Never skip this step
    • Store backups off-site
    • Test restoration regularly
  2. Use Staging Environment
    • Test cleanups on staging first
    • Verify results before production
    • Practice safe deployment
  3. Limit User Access
    • Only administrators should access plugin
    • Review user roles regularly
    • Use principle of least privilege
  4. Monitor Changes
    • Document cleanup operations
    • Track database size changes
    • Keep operation logs
  5. Schedule Off-Peak Operations
    • Low traffic times
    • Maintenance windows
    • User notification in advance

Backup Strategy

3-2-1 Backup Rule:

  • 3 copies of data
  • 2 different storage types
  • 1 off-site backup

Recommended Backup Schedule:

  • Before every cleanup: Manual backup
  • Daily: Automated hosting backups
  • Weekly: Full site backup to external storage
  • Monthly: Archive backup for long-term storage

Backup Tools:

  • Free: UpdraftPlus, BackWPup
  • Premium: BackupBuddy, WP Time Capsule, BlogVault
  • Hosting: cPanel backups, host-specific tools
  • Manual: phpMyAdmin export, WordPress export

Content Management Guidelines

Post Revisions

Optimal Strategy:

  • Keep 3-5 most recent revisions
  • Delete revisions older than 30-60 days
  • Document major edits externally

wp-config.php Settings:

// Limit revisions to 5
define('WP_POST_REVISIONS', 5);

// Or disable revisions entirely
define('WP_POST_REVISIONS', false);

Comments

Moderation Best Practices:

  • Review pending comments weekly
  • Empty trash monthly
  • Clean spam weekly
  • Use Akismet or similar anti-spam

Auto-Delete Settings:

  • Don’t rely on auto-delete alone
  • Manual review recommended
  • Keep legitimate comments indefinitely

Media Management

Note: WP Optimal State doesn’t manage media files

Complementary Practices:

  • Use media cleanup plugins for unused images
  • Optimize images before upload
  • Regular media library audits
  • Remove unused media monthly

FAQ

General Questions

Q: Is WP Optimal State safe to use?

A: Yes, when used properly. Always create a backup before cleaning, and start with the One-Click Optimization which only performs safe operations. Items marked with ⚠️ require extra caution.


Q: Will this plugin speed up my website?

A: Yes, typically you’ll see:

  • Faster admin dashboard (10-30% improvement)
  • Reduced database query times (15-40% improvement)
  • Smaller backup sizes
  • Better hosting resource usage

Front-end speed improvements are typically 5-15% when combined with caching plugins.


Q: How often should I clean my database?

A: Recommended schedule:

  • Weekly: One-Click Optimization
  • Monthly: Full manual cleanup
  • Quarterly: Deep maintenance with all options

High-traffic sites may benefit from twice-weekly cleanups.


Q: Can I undo a cleanup operation?

A: No, cleanup operations permanently delete data. This is why backups are critical. Always backup before cleaning, and test on staging sites when possible.


Q: Will this affect my published content?

A: No, safe operations (without ⚠️ warning) only remove:

  • Old revisions
  • Deleted content
  • Spam
  • Orphaned data
  • Expired cache

Your published posts, pages, and approved comments remain untouched.


Q: Does this work with WooCommerce?

A: Yes, WP Optimal State is compatible with WooCommerce and other plugins. It works at the database level and respects all WordPress data structures.


Q: Will this delete my images/media files?

A: No, WP Optimal State only cleans database entries. Media files in wp-content/uploads are not affected. Use a dedicated media cleanup plugin for unused files.


Q: Can I schedule automatic cleanups?

A: Currently, automatic scheduling is not enabled in the interface. You can manually run cleanups or use WordPress cron jobs. Scheduled cleanup functionality may be added in future versions.


Q: What’s the difference between “Expired Transients” and “All Transients”?

A:

  • Expired Transients: Cached data past expiration time – safe to delete
  • All Transients: All cached data including active cache – may temporarily slow site while rebuilding

Always clean expired transients first.


Q: How much database space will I save?

A: Varies by site:

  • Small blogs: 5-20% reduction
  • Active blogs: 20-40% reduction
  • E-commerce sites: 10-30% reduction
  • Large forums: 30-50% reduction

Sites with many revisions see the most dramatic results.


Q: Is this plugin compatible with multisite?

A: The plugin is designed for single-site installations. Multisite compatibility has not been tested and is not officially supported.


Q: Does this work with managed WordPress hosting?

A: Yes, but some managed hosts (WP Engine, Kinsta) may have restrictions on database operations. Check with your host if you experience issues.


Technical Questions

Q: What MySQL/MariaDB permissions are required?

A: The plugin requires standard WordPress database permissions:

  • SELECT
  • INSERT
  • UPDATE
  • DELETE
  • CREATE
  • DROP
  • ALTER

These are typically included with WordPress installation.


Q: Can I use this on a production site?

A: Yes, but follow these rules:

  1. Always backup first
  2. Test on staging if possible
  3. Run during low-traffic periods
  4. Monitor site after cleanup
  5. Have recovery plan ready

Q: Does this plugin create new database tables?

A: No, WP Optimal State doesn’t create any new tables. It only cleans and optimizes existing WordPress tables.


Q: Will this conflict with other optimization plugins?

A: Generally no, but avoid running multiple cleanup operations simultaneously. Disable other database cleanup plugins before using WP Optimal State, or use them at different times.


Q: What happens to the data that’s deleted?

A: Data is permanently removed from the database via SQL DELETE commands. It’s not moved to trash or marked as deleted – it’s completely erased.


Q: Can I recover data after cleaning?

A: Only from backups. Once cleaned, data cannot be recovered from the plugin. Always maintain recent backups.


Q: Does this plugin log what it deletes?

A: The plugin shows real-time counts of deleted items in the results panel. For detailed logging, enable WordPress debug mode before cleaning.


Q: What’s the maximum database size this can handle?

A: There’s no hard limit, but very large databases (10GB+) may need:

  • Increased PHP timeout settings
  • More server memory
  • CLI-based cleanup for best results

Q: Does this work with custom post types?

A: Yes, cleanup operations work on all post types including custom post types. Revisions, metadata, and relationships are cleaned regardless of post type.


Q: Will this delete plugin settings?

A: Safe operations won’t delete plugin settings. The “Optimize Autoloaded Options” feature specifically excludes critical options like active_plugins. Plugin settings are preserved unless you manually clean “All Transients” which may clear some cached settings.


Troubleshooting Questions

Q: Why do statistics show 0 but database is still large?

A: Database size includes:

  • Table structure overhead
  • Non-cleanable data (posts, comments, users)
  • Media metadata
  • Plugin/theme data
  • MySQL storage engine overhead

Not all database content should be cleaned.


Q: The plugin says “Cleaned 500 items” but I don’t see a difference?

A: Run “Optimize All Tables” afterward. MySQL doesn’t immediately release space – it marks it as reusable. Table optimization reclaims this space.


Q: Why won’t my autoload size decrease?

A: Some large autoloaded options are:

  1. Protected by the plugin (active_plugins, cron, rewrite_rules)
  2. Recreated immediately by plugins
  3. Required for site functionality

Focus on identifying and replacing problematic plugins.


Q: Site got slower after cleaning transients?

A: Normal for 1-2 hours while cache rebuilds. Solutions:

  • Visit all main pages to regenerate cache
  • Wait for cache to rebuild naturally
  • Clear browser cache
  • Flush object cache if using Redis/Memcached

Q: Getting “Out of Memory” errors?

A: Increase PHP memory:

In wp-config.php:

define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');

Or contact hosting provider to increase:

  • memory_limit
  • php_memory_limit

Q: Operations timeout on my site?

A: Your hosting may have strict limits. Options:

  1. Contact host to temporarily increase limits
  2. Clean smaller batches manually
  3. Upgrade hosting plan
  4. Use WP-CLI for large operations
  5. Schedule during off-peak hours

Q: Can’t access plugin page after activation?

A: Check:

  1. You have administrator role
  2. WordPress is updated
  3. PHP version meets requirements (7.0+)
  4. No plugin conflicts (deactivate others temporarily)
  5. No .htaccess restrictions

Technical Information

System Requirements

Minimum Requirements:

  • WordPress: 5.0 or higher
  • PHP: 7.0 or higher
  • MySQL: 5.6 or higher (or MariaDB 10.0+)
  • Memory: 64MB PHP memory minimum
  • User Role: Administrator

Recommended Requirements:

  • WordPress: 6.0 or higher
  • PHP: 8.0 or higher
  • MySQL: 5.7 or higher (or MariaDB 10.3+)
  • Memory: 128MB+ PHP memory
  • Storage: SSD-based hosting
  • Backup: Automated daily backups

Database Operations

Tables Modified

The plugin can clean data from these WordPress core tables:

Table Operations
wp_posts Delete revisions, auto-drafts, trash
wp_postmeta Remove orphaned and duplicate meta
wp_comments Delete spam, trash, pingbacks, trackbacks
wp_commentmeta Remove orphaned and duplicate meta
wp_usermeta Clean orphaned user metadata
wp_term_relationships Delete orphaned relationships
wp_options Clean transients, optimize autoload

All Tables: Can be optimized with OPTIMIZE TABLE command


SQL Queries Used

Sample queries (simplified):

-- Count post revisions
SELECT COUNT(*) FROM wp_posts WHERE post_type = 'revision';

-- Delete post revisions
DELETE FROM wp_posts WHERE post_type = 'revision';

-- Find orphaned postmeta
SELECT COUNT(*) FROM wp_postmeta 
WHERE post_id NOT IN (SELECT ID FROM wp_posts);

-- Clean expired transients
DELETE FROM wp_options 
WHERE option_name LIKE '_transient_timeout_%' 
AND option_value < UNIX_TIMESTAMP();

-- Optimize table
OPTIMIZE TABLE wp_posts;

Performance Impact

During Operation

Resource Usage:

  • CPU: Moderate (30-60% for 10-60 seconds)
  • Memory: Based on data size (typically 64-256MB)
  • Disk I/O: High during table optimization
  • Database: Table locks during operations

Site Impact:

  • Brief slowdowns during cleanup (1-30 seconds)
  • Table locks may delay queries momentarily
  • Minimal impact on front-end for visitors
  • Admin may be slower during operations

After Operation

Expected Improvements:

  • Database size: 10-50% reduction (varies)
  • Query speed: 15-40% faster
  • Admin speed: 10-30% improvement
  • Backup time: 20-40% reduction
  • Hosting storage: Lower usage

Security Features

Built-in Protections

  1. Nonce Verification
    • All AJAX requests verified
    • Prevents CSRF attacks
    • 24-hour token expiration
  2. Capability Checks
    • Requires ‘manage_options’ capability
    • Administrator role only
    • Per-request verification
  3. Input Sanitization
    • All user input sanitized
    • SQL injection prevention
    • XSS protection
  4. Output Escaping
    • All output escaped
    • HTML injection prevention
    • JavaScript safety
  5. Prepared Statements
    • Uses $wpdb->prepare() for dynamic queries
    • Parameterized queries
    • SQL injection prevention

Compatibility

WordPress Versions

  • Minimum: 5.0
  • Tested up to: 6.7
  • Recommended: 6.0+

PHP Versions

  • Minimum: 7.0
  • Tested: 7.0, 7.4, 8.0, 8.1, 8.2
  • Recommended: 8.0+

Database Systems

  • MySQL: 5.6, 5.7, 8.0
  • MariaDB: 10.0, 10.3, 10.5, 10.6
  • Percona: Compatible with MySQL versions

Known Compatible Plugins

  • WooCommerce
  • Yoast SEO
  • Contact Form 7
  • Advanced Custom Fields
  • Elementor
  • WPBakery
  • Jetpack
  • Wordfence
  • All major caching plugins

Known Incompatibilities

  • None currently identified
  • Report any issues to support

File Structure

wp-optimal-state/
├── wp-optimal-state.php    # Main plugin file
├── css/
│   └── admin-styles.css    # Admin interface styles
├── languages/              # Translation files (future)
│   └── wp-optimal-state.pot
├── readme.txt              # WordPress.org readme
└── LICENSE.txt             # GPL v2 license

Hooks & Filters

Available Actions

wpos_scheduled_cleanup

  • Triggered by scheduled cleanup (if configured)
  • Can be used for custom automation

Example:

add_action('wpos_scheduled_cleanup', 'my_custom_cleanup');
function my_custom_cleanup() {
    // Custom cleanup code
}

WP-CLI Usage (Advanced)

For very large databases, consider using WP-CLI:

# Optimize all tables
wp db optimize

# Clean transients (requires plugin)
wp transient delete --expired

# Export database
wp db export backup.sql

# Clean post revisions (requires custom command)
wp post list --post_type=revision --format=ids | xargs wp post delete

Advanced Configuration

Increase Operation Limits

In wp-config.php:

// Increase memory
define('WP_MEMORY_LIMIT', '256M');
define('WP_MAX_MEMORY_LIMIT', '512M');

// Increase execution time
set_time_limit(300);
ini_set('max_execution_time', 300);

// Limit post revisions
define('WP_POST_REVISIONS', 5);

// Or disable revisions
define('WP_POST_REVISIONS', false);

Database Configuration

For large databases, optimize MySQL/MariaDB:

# my.cnf or my.ini
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
query_cache_size = 64M
query_cache_type = 1
table_open_cache = 2000
max_connections = 200

Note: Restart MySQL after configuration changes.


Support

Getting Help

Self-Help Resources

  1. This Manual
    • Comprehensive feature documentation
    • Troubleshooting section
    • FAQ with common issues
  2. WordPress.org Support Forum
    • Community support
    • Search existing topics
    • Post new questions
    • URL: wordpress.org/support/plugin/wp-optimal-state
  3. Plugin Website

Before Requesting Support

Prepare this information:

  1. WordPress Details
    • WordPress version
    • PHP version
    • Database type and version
    • Hosting provider
  2. Plugin Information
    • WP Optimal State version
    • Active plugins list
    • Active theme
  3. Issue Details
    • What you were trying to do
    • What happened instead
    • Error messages (exact text)
    • Screenshots if relevant
  4. Troubleshooting Steps Taken
    • What you’ve already tried
    • Results of each attempt
  5. Environment
    • Database size
    • Number of posts
    • Recent changes to site

Enable Debug Mode:

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

Check wp-content/debug.log for errors.


Reporting Bugs

How to Report

  1. Verify It’s a Bug
    • Test on default WordPress theme
    • Deactivate other plugins
    • Clear all caches
    • Try different browser
  2. Check Existing Reports
    • Search support forum
    • Check GitHub issues (if applicable)
    • Avoid duplicate reports
  3. Provide Complete Information
    Bug Report Template:
    
    **Expected Behavior:**
    What should happen
    
    **Actual Behavior:**
    What actually happens
    
    **Steps to Reproduce:**
    1. Go to...
    2. Click on...
    3. See error
    
    **Environment:**
    - WordPress: 6.4
    - PHP: 8.1
    - Plugin Version: 1.0.2
    - Database: MySQL 5.7
    
    **Error Messages:**
    [Paste any error messages]
    
    **Screenshots:**
    [Attach if relevant]
    
  4. Submit Report
    • WordPress.org support forum
    • Plugin author contact form
    • Include all information above

Feature Requests

Requesting New Features

  1. Check Roadmap
    • Review planned features
    • Search existing requests
  2. Describe Use Case
    • Explain the problem
    • Why feature is needed
    • How it would work
    • Who would benefit
  3. Submit Request
    • Support forum
    • Plugin website contact
    • Be specific and detailed

Contributing

How to Contribute

  1. Translations
    • Plugin is translation-ready
    • Use translate.wordpress.org
    • Submit translations for your language
  2. Documentation
    • Report errors in manual
    • Suggest improvements
    • Share tutorials
  3. Testing
    • Test new versions
    • Report compatibility issues
    • Beta test new features
  4. Code Contributions
    • Submit patches for bugs
    • Propose improvements
    • Follow WordPress coding standards

Privacy & Data Collection

What Data Does the Plugin Collect?

None. WP Optimal State:

  • Does NOT track users
  • Does NOT send data to external servers
  • Does NOT use cookies
  • Does NOT collect analytics
  • Does NOT include third-party tracking
  • Operates entirely locally

All database operations are performed on your WordPress installation only.


License Information

License: GNU General Public License v2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

What This Means:

  • Free to use
  • Free to modify
  • Free to distribute
  • Commercial use allowed
  • Must maintain GPL license

You are free to:

  • Use the plugin on unlimited sites
  • Modify the code
  • Create derivative works
  • Charge for your modifications

You must:

  • Keep the GPL license
  • Provide source code
  • Credit original authors

Appendix

Glossary of Terms

Auto-draft: Automatically saved draft posts created while you type

Autoload: Options loaded into memory on every page request

Database Optimization: Process of improving database performance and reducing size

InnoDB: MySQL storage engine (default in modern WordPress)

Metadata: Additional information attached to posts, comments, or users

MyISAM: Older MySQL storage engine

Nonce: Security token to prevent CSRF attacks

Orphaned Data: Database entries referencing deleted items

phpMyAdmin: Web interface for managing MySQL databases

Post Meta: Custom fields attached to posts

Revision: Saved version of post/page from editing

Slug: URL-friendly name (e.g., “wp-optimal-state”)

Transient: Temporary cached data with expiration time

WP-CLI: Command-line interface for WordPress


Useful SQL Queries

For advanced users to run in phpMyAdmin:

-- Check database size
SELECT 
    table_schema AS 'Database',
    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
GROUP BY table_schema;

-- Find largest tables
SELECT 
    table_name AS 'Table',
    ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size (MB)'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
ORDER BY (data_length + index_length) DESC
LIMIT 10;

-- Count rows in each table
SELECT 
    table_name AS 'Table',
    table_rows AS 'Rows'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
ORDER BY table_rows DESC;

-- Find large autoloaded options
SELECT 
    option_name,
    LENGTH(option_value) AS size
FROM wp_options
WHERE autoload = 'yes'
ORDER BY size DESC
LIMIT 10;

-- Check table fragmentation
SELECT 
    table_name AS 'Table',
    ROUND(data_free / 1024 / 1024, 2) AS 'Fragmented (MB)'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
AND data_free > 0
ORDER BY data_free DESC;

⚠️ Warning: Only run these queries if you understand SQL. Incorrect queries can damage your database.


Resources

Official WordPress Resources

Database Optimization

Performance Testing

Backup Solutions


Version History

Version 1.0.2 (Current)

  • Added internationalization support
  • Improved security (escaping, sanitization)
  • Enhanced SQL query preparation
  • Updated for WordPress 6.7
  • Documentation improvements

Version 1.0.1

  • Initial public release
  • One-click optimization feature
  • Improved user interface
  • Autoload optimization
  • Enhanced statistics display

Version 1.0.0

  • Initial development release
  • Core cleanup functionality
  • Database table optimization
  • Basic statistics

Credits

Developed By: Luke Garrison 🔗 – The Spiritual Seek
Website: spiritualseek.com
Plugin URI: spiritualseek.com/wp-optimal-state-wordpress-plugin/
License: GPL v2 or later

Built With:

  • WordPress Core APIs
  • jQuery (bundled with WordPress)
  • CSS3 and modern web standards

Special Thanks:

  • WordPress community
  • Beta testers
  • Translators
  • Support forum contributors

Contact Information

Plugin Support: WordPress.org support forum
Website: spiritualseek.com
Contact Form: spiritualseek.com/contacts/
Plugin Page: spiritualseek.com/wp-optimal-state-wordpress-plugin/

For support requests, please use the WordPress.org support forum. For business inquiries, use the contact form on our website.


Conclusion

Thank you for using WP Optimal State! This plugin is designed to make WordPress database maintenance simple, safe, and effective. By following the guidelines in this manual, you can keep your website running at peak performance.

Key Takeaways

  1. Always backup before cleaning
  2. Start with safe operations (One-Click Optimization)
  3. Clean regularly (weekly recommended)
  4. Monitor results and adjust frequency
  5. Review warnings before potentially destructive operations

Getting the Most from WP Optimal State

  • Establish a regular maintenance schedule
  • Keep backups current
  • Monitor database statistics
  • Combine with other optimization techniques
  • Test on staging environments first

Stay Updated

  • Watch for plugin updates in WordPress admin
  • Check changelog for new features
  • Review support forum for tips
  • Visit plugin website for tutorials

Happy Optimizing!


WP Optimal State – Keep Your WordPress Database Clean and Fast

Documentation Version: 1.0.2
Last Updated: October 2025
Applicable to Plugin Version: 1.0.2 and above


End of Manual