A WordPress database cleanup paired with a properly tuned Cloudflare setup is the fastest low-cost speed upgrade most sites will ever get. Bloated tables slow every uncached request, while a misconfigured Cloudflare zone either caches too little to help or blocks the very crawlers a site depends on for search traffic and ad revenue. This tutorial walks through both halves in the order that matters: protect the site with a backup, measure the database, clean it safely with SQL, WP-CLI, or a plugin, then configure Cloudflare bot rules, cache rules, and edge HTML caching so the lighter database is hit far less often.
Every step below is written for a standard WordPress install on shared, VPS, or managed hosting with phpMyAdmin or SSH access. The queries assume the default wp_ table prefix, so swap in the real prefix from wp-config.php if the site uses a custom one. Nothing here requires a paid tool, although the Top 10 section later compares the free and premium options that automate each part.
Why WordPress Database Cleanup and Cloudflare Optimization Belong Together
Most tutorials treat these as separate jobs. That misses how they interact. Cloudflare can only serve a page from its edge when the page is cacheable; every cache miss, logged-in visit, search query, cart action, or bot request that bypasses the cache still lands on PHP and MySQL. A lean database makes those unavoidable origin hits cheap. A strong cache layer, in turn, means fewer queries reach the database in the first place, so tables grow more slowly and cleanup intervals stretch out.
The payoff shows up in Time to First Byte, which feeds directly into Largest Contentful Paint and therefore Core Web Vitals. It also shows up in crawl behaviour. When Googlebot, Bingbot, and advertising crawlers receive fast, consistent responses instead of challenges or timeouts, pages get indexed and ads get matched to content more reliably.
What Actually Bloats a WordPress Database
Four sources account for the bulk of avoidable growth on a typical content site. Post revisions pile up in wp_posts every time an article is saved. Transients, which plugins use as short-lived caches, accumulate in wp_options when they expire but are never purged. Autoloaded options, loaded on every single page request, balloon when plugins store large settings arrays or leave data behind after being uninstalled. Finally, analytics and logging plugins write rows constantly: post view counters, SEO analytics tables, security logs, and email logs can quietly outgrow the actual content.
Orphaned metadata is the silent fifth category. When posts are deleted outside the normal WordPress flow, or when a plugin removes its own records carelessly, rows in wp_postmeta and wp_commentmeta can point to parents that no longer exist. They serve no purpose and still get scanned by queries.
Part 1: Back Up and Measure Before Touching Anything
Every DELETE in this tutorial is permanent. Take a full database export before running a single query, and store it somewhere other than the web server. A copy of wp-content alone does not protect the database.
Step 1: Export the Database
- Open phpMyAdmin from the hosting control panel and select the WordPress database in the left sidebar.
- Click the Export tab, choose the Quick method and SQL format, then click Export and save the file locally.
- If SSH access is available, run the WP-CLI command below from the WordPress root instead; it is faster and does not time out on large databases.
wp db export backup-before-cleanup.sql
Step 2: Find the Largest Tables
Cleanup without measurement is guesswork. Open the SQL tab in phpMyAdmin and run this query, replacing your_database_name with the database name shown in the sidebar:
SELECT table_name, ROUND((data_length + index_length) / 1024 / 1024, 2) AS size_mb, ROUND(data_free / 1024 / 1024, 2) AS free_mb FROM information_schema.tables WHERE table_schema = 'your_database_name' ORDER BY (data_length + index_length) DESC LIMIT 15;
The size_mb column shows where the weight actually sits. The free_mb column shows space already released by deletions but not yet returned to the operating system, which is what OPTIMIZE TABLE recovers later. Record the total before starting so the result can be compared afterwards.
Step 3: Measure Autoloaded Options
Autoloaded data is loaded into memory on every uncached request, so it deserves its own check. WordPress 6.6 changed the autoload column from simple yes and no values to a wider set that includes on, auto-on, and auto, so the query needs to account for both the old and new values:
SELECT ROUND(SUM(LENGTH(option_value)) / 1024, 2) AS autoload_kb FROM wp_options WHERE autoload IN ('yes', 'on', 'auto-on', 'auto');
A widely used target is keeping the total under roughly 800 KB. If the figure is higher, list the heaviest offenders:
SELECT option_name, ROUND(LENGTH(option_value) / 1024, 2) AS size_kb FROM wp_options WHERE autoload IN ('yes', 'on', 'auto-on', 'auto') ORDER BY LENGTH(option_value) DESC LIMIT 20;
Option names usually carry the plugin’s prefix. Anything belonging to a plugin that has already been removed is a safe candidate for deletion. Anything belonging to an active plugin should be left alone or switched to not autoload only after confirming the plugin reads it on demand.
Part 2: Clean the WordPress Database Step by Step
Work through the steps in order. Each targets one bloat source, and each is safe on its own, so it is fine to stop after any step and test the site.
Step 4: Delete Expired Transients
Expired transients are pure waste. The cleanest method is WP-CLI, which removes only the expired entries and leaves active ones intact:
wp transient delete --expired
Without SSH, a plugin such as WP-Optimize or WP-Sweep performs the same job from the dashboard. Deleting every transient with a broad SQL LIKE pattern also works, but it clears active caches too, so plugins will rebuild them on the next few page loads and the site may feel briefly slower.
Step 5: Prune Post Revisions
Revisions are useful for undoing mistakes on recent edits and useless on articles published years ago. To delete all existing revisions through WP-CLI:
wp post delete $(wp post list --post_type=revision --format=ids) --force
On sites with tens of thousands of revisions the ID list can exceed the shell’s argument limit. In that case, the Revisions option in WP-Optimize or WP-Sweep handles the batching automatically. Once the backlog is gone, Step 11 prevents it from returning.
Step 6: Remove Orphaned Post Meta
This query deletes metadata rows whose parent post no longer exists. Run the SELECT version first to see how many rows it will touch:
SELECT COUNT(*) FROM wp_postmeta pm LEFT JOIN wp_posts p ON p.ID = pm.post_id WHERE p.ID IS NULL;
If the count looks sensible, remove them:
DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts p ON p.ID = pm.post_id WHERE p.ID IS NULL;
Step 7: Trim the Post Views Table
View-counter plugins such as Post Views Counter store one row per post per period, which grows endlessly on a busy site. Keeping the most recent 30 days is enough for trending widgets and popular-post lists:
- Open phpMyAdmin, select the database, and click the SQL tab.
- Run the cleanup query:
DELETE FROM wp_post_views WHERE period < DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 30 DAY), '%Y%m%d');
- Rebuild the table so the freed space is released:
OPTIMIZE TABLE wp_post_views;
Check the plugin’s own documentation before running this if total all-time view counts are displayed publicly. Many counters store the all-time total in a separate row, but some themes calculate it from the daily rows.
Step 8: Clean Rank Math Analytics Tables
Rank Math’s Analytics module pulls Google Search Console data into local tables, and the inspections table grows with every URL Inspection API check. Keeping 60 days of history covers most reporting needs:
- Remove Search Console rows older than 60 days:
DELETE FROM wp_rank_math_analytics_gsc WHERE created < DATE_SUB(NOW(), INTERVAL 60 DAY);
- Rebuild the table:
OPTIMIZE TABLE wp_rank_math_analytics_gsc;
- Remove old inspection records:
DELETE FROM wp_rank_math_analytics_inspections WHERE created < DATE_SUB(NOW(), INTERVAL 60 DAY);
- Rebuild the inspections table:
OPTIMIZE TABLE wp_rank_math_analytics_inspections;
After the manual cleanup, open Rank Math then General Settings then the Analytics tab, find the data retention setting, and set it to 60 days. The plugin will then purge older rows on its own, so the manual queries become a fallback rather than a routine.
Step 9: Understand What OPTIMIZE TABLE Really Does
This is the step most guides get wrong, and it explains the most common complaint: the database did not shrink. For InnoDB tables, which every modern WordPress install uses, OPTIMIZE TABLE rebuilds the table and its indexes by copying the rows into a fresh copy. When the server runs with innodb_file_per_table enabled, each table has its own file on disk and the rebuild hands the freed space back to the operating system, a behaviour documented in the MySQL OPTIMIZE TABLE reference.
When that setting is off, all tables share one system tablespace, and the space is reused internally for new rows but the file on disk never gets smaller. Performance still improves because indexes are rebuilt and fragmentation is removed, yet the hosting panel’s disk usage figure stays flat. phpMyAdmin may also display the note that the table does not support optimize and is doing a recreate plus analyze instead. That message is normal for InnoDB and means the operation succeeded.
Step 10: Check the Results
- Rerun the table size query from Step 2.
- Compare the new total and the
free_mbcolumn against the numbers recorded before cleanup. - Load the homepage, a single post, the admin dashboard, and any forms to confirm nothing broke.
The size reduction depends entirely on how much of the database was bloat. A site where view counters and analytics tables made up most of the weight can drop by a large share of its total; a site with tidy plugins may see only a small change but still gain faster queries on the tables that matter.
Part 3: Stop the Bloat From Coming Back
Step 11: Limit Revisions and Shorten Trash Retention in wp-config.php
- Open the hosting File Manager or connect via SFTP.
- Navigate to the WordPress root, usually
public_html, and openwp-config.phpfor editing. - Add the lines below above the comment line that reads “That’s all, stop editing!”
- Save the file.
define( 'WP_POST_REVISIONS', 5 );
define( 'EMPTY_TRASH_DAYS', 7 );
Capping revisions at a small number keeps the safety net for recent edits without the long tail. Setting the constant to false disables revisions entirely, which is what the earlier version of this guide recommended; that is reasonable on single-author sites with a reliable backup routine, but risky anywhere editors collaborate. The official WordPress wp-config documentation notes that some setups only honour the revisions constant when it sits near the top of the file, so move it higher if revisions keep appearing. The trash constant makes WordPress permanently empty trashed posts and comments after seven days instead of the default thirty.
Part 4: Cloudflare Bot Protection That Lets Good Crawlers Through
Aggressive bot settings are the most common way a Cloudflare setup quietly damages a WordPress site. Super Bot Fight Mode, managed rules, and rate limits can challenge legitimate crawlers, and a challenged crawler cannot read the page. The fix is a single skip rule, placed first, that exempts verified bots from everything below it.
Step 12: Create the Verified Bots Skip Rule
- In the Cloudflare dashboard, open the site and go to Security then Security rules (labelled WAF then Custom rules on older dashboards).
- Click Create rule and name it Allow Verified Bots.
- Click Edit expression and paste the expression below.
(cf.client.bot) or (cf.verified_bot_category in {"Search Engine Crawler" "Search Engine Optimization" "AI Search" "AI Assistant" "Advertising & Marketing" "Monitoring & Analytics" "Feed Fetcher" "Page Preview"})
- Under Then take action, choose Skip.
- Tick All remaining custom rules, All rate limiting rules, All managed rules, and All Super Bot Fight Mode rules.
- Set Place at to First and click Deploy.
The cf.client.bot field matches any bot Cloudflare has verified, while the category field lets the rule be explicit about which kinds of verified traffic are welcome. Cloudflare’s verified bots documentation lists every category string, including AI Crawler, which is deliberately left out here. Training crawlers consume bandwidth without sending visitors, whereas AI Search and AI Assistant fetchers retrieve pages to answer live user questions and can cite the source.
Two refinements are worth considering. Adding the site owner’s own static office IP with an or (ip.src eq ...) clause stops the owner being challenged while testing. Matching crawlers by user agent string alone, which many older guides suggest, is unsafe because any scraper can fake a user agent; verified bot fields are checked by Cloudflare against the crawler’s real network identity.
Part 5: Cloudflare Cache Rules for WordPress
Cloudflare caches static files by extension out of the box but, as its default cache behavior documentation confirms, does not cache HTML by default. That means a plain orange-cloud setup speeds up images, CSS, and JavaScript but still sends every page view to the origin. The three rules below fix that safely, and Cache Rules are available on every plan including Free.
Step 13: Bypass the Cache for Admin and Logged-In Users
This rule must exist before any rule that caches HTML, otherwise editors can be served stale admin pages and logged-out visitors can be served a page containing someone else’s admin bar.
- Go to Caching then Cache Rules and click Create rule.
- Name it Bypass Admin and Logged In.
- Paste this expression:
(starts_with(http.request.uri.path, "/wp-admin")) or (http.request.uri.path eq "/wp-login.php") or (http.request.uri.path contains "/wp-json/") or (http.cookie contains "wordpress_logged_in") or (http.cookie contains "wp-postpass") or (http.cookie contains "comment_author") or (http.cookie contains "woocommerce_items_in_cart")
- Set Cache eligibility to Bypass cache and deploy.
Step 14: Cache Static Assets for a Month
- Create a second cache rule named Long Cache for Static Assets.
- Paste this expression:
(http.request.uri.path.extension in {"jpg" "jpeg" "png" "gif" "webp" "avif" "svg" "css" "js" "ico" "woff" "woff2" "ttf" "eot" "mp4"})
- Set Cache eligibility to Eligible for cache.
- Set Edge TTL to ignore the origin header and use 1 month.
- Set Browser TTL to override the origin and use 1 month, then deploy.
A month-long browser TTL is safe because WordPress appends a version query string to theme and plugin assets, so updated files get a new URL. Images replaced under the same filename are the exception; upload replacements with a new name.
Step 15: Cache HTML at the Edge With APO or a Cache Rule
Caching the HTML itself is where the largest Time to First Byte gains come from. There are two routes. Cloudflare Automatic Platform Optimization, installed through the official Cloudflare WordPress plugin, caches pages at the edge, recognises WordPress login cookies automatically, and purges changed pages when a post is updated. It costs $5 per month on the Free plan and is included in Pro, which lists at $20 per month billed annually or $25 billed monthly. Cloudflare recommends disabling other page caching plugins while setting it up, then re-enabling features one at a time.
The free route is a third cache rule placed after the bypass rule, matching the hostname, set to Eligible for cache, with an Edge TTL of a few hours. Its weakness is purging: nothing tells Cloudflare a post changed, so either the TTL must stay short or a plugin such as Super Page Cache must be installed to purge the right URLs automatically. To confirm APO is working, load a page in a private window with DevTools cache disabling switched off and check the response headers; cf-cache-status: HIT together with a cf-apo-via value of tcache means the page came from the edge.
Step 16: Set Browser Cache TTL and Purge
- Go to Caching then Configuration.
- Set Browser Cache TTL to Respect Existing Headers if cache rules now control assets, or to 1 day as a zone-wide default if they do not.
- Click Purge Everything and confirm, so the new rules apply to fresh copies.
Troubleshooting WordPress Database Cleanup and Cloudflare Issues
If search features or crawlers still fail after the bot rule, give it half an hour, then open Security then Events and filter by the rule name. Legitimate crawlers should appear with a Skip action; if Googlebot is still challenged, check that the skip rule sits above every other custom rule and that Bot Fight Mode on the Free plan has not been switched on, since the free Bot Fight Mode cannot be bypassed by custom rules.
When the database size barely moves after OPTIMIZE TABLE, the cause is almost always a shared InnoDB tablespace, as covered in Step 9. Query speed improves regardless. Hosts can enable file-per-table storage, but existing tables only move into their own files after being rebuilt once the setting is on.
If logged-in users see cached pages or a cart empties unexpectedly, the bypass rule is either missing a cookie name or ordered below the HTML cache rule. Rule order in Cloudflare matters, and later matching rules can override settings from earlier ones. Ad revenue and indexing improvements, where they come, take weeks rather than days because crawlers must revisit pages before rankings and ad matching update.
Top 10 WordPress Database Cleanup and Cloudflare Optimization Tools
The tools below were ranked by how much of this tutorial each one automates, how safely it does it, and how much it costs to keep running. Free tools that cover a single job well sit alongside premium suites that bundle caching, cleanup, and asset optimisation, so every budget has a clear pick.
1. Cloudflare APO — Best for Edge HTML Caching
Automatic Platform Optimization serves entire WordPress pages from Cloudflare’s network, so most visitors never touch PHP or MySQL at all. It suits any content-heavy site on a Cloudflare zone that wants the largest possible TTFB improvement with the least configuration. Its standout strength is automatic purging on post updates, which the free cache-rule route lacks. APO costs $5 per month on the Free plan and is included with Pro at $20 per month billed annually.
- Caches full HTML at the edge with WordPress-aware cookie bypass
- Automatic purge of changed content through the official plugin
- Proxies Google Fonts through the site’s own domain
- Verification headers for confirming cache hits
The biggest strength is how little tuning it needs compared with hand-built cache rules. The real weakness is compatibility: Cloudflare itself advises turning off other caching plugins during setup, and sites with heavy personalisation or unusual login flows can see stale or bypassed pages until exceptions are worked out.
2. WP-Optimize — Best All-in-One Cleanup and Caching Plugin
WP-Optimize combines database cleanup, page caching, image compression, and minification in one plugin with more than a million active installs. It fits site owners who want revisions, transients, spam, and table optimisation handled from a single screen on a schedule. The standout is scheduled cleanup that runs without SSH or SQL. The core plugin is free, and the premium version starts at $49 per year for a single site.
- One-click cleanup of revisions, drafts, spam, and expired transients
- Scheduled automatic database optimisation
- Built-in page cache, minification, and WebP conversion
- Table-level view with per-table optimise actions
Its breadth is the draw, since one plugin replaces three or four. The weakness is overlap: sites already running WP Rocket, FlyingPress, or APO should disable WP-Optimize’s cache and minify modules to avoid conflicting layers, which leaves the database tools as the only part in use.
3. Advanced Database Cleaner — Best for Orphaned Options and Tables
Advanced Database Cleaner goes further than most cleaners by identifying which plugin owns each option, table, and cron job, including leftovers from plugins removed long ago. It suits older sites that have cycled through many plugins and carry an autoload problem nobody can trace. The ownership detection is the reason to rank it here. The core plugin is free on WordPress.org, with a paid Pro licence that adds the ownership scanner and advanced filters.
- Detects orphaned options, tables, and scheduled tasks
- Shows autoload size and lets options be switched off
- Scheduled cleanup of revisions, transients, and spam
- Per-table optimise and repair actions
Nothing else in the free tier comes as close to showing where autoload bloat originates. The weakness is that the most useful feature, plugin ownership detection, sits behind the Pro licence, and its guesses still need a human check before deleting anything.
4. WP-Sweep — Best Free Lightweight Cleaner
WP-Sweep cleans revisions, auto-drafts, orphaned meta, duplicated meta, and transients using WordPress’s own delete functions rather than raw SQL. That approach fits cautious site owners because hooks fire normally and related records are removed together. Its standout strength is that safety-first design in a very small plugin. WP-Sweep is completely free.
- Uses native WordPress delete functions instead of direct queries
- Cleans orphaned and duplicated post, comment, user, and term meta
- Counts every category before sweeping
- WP-CLI command support for scripted cleanup
It is the safest single-purpose cleaner available at no cost. The weakness is scope: there is no scheduler, no autoload analysis, and no table optimisation, so it covers the cleanup steps but not the measurement or rebuild steps.
5. Query Monitor — Best for Finding the Real Bottleneck
Query Monitor is a developer tools panel that shows every database query on a page, which component ran it, how long it took, and whether it was duplicated. It suits anyone who has cleaned the database and still sees slow admin pages. Its standout is attributing slow queries to a specific plugin or theme. The plugin is free.
- Lists queries by plugin, theme, and core component
- Flags slow, duplicate, and failed queries
- Shows hooks, HTTP API calls, and PHP errors
- Reports object cache hit rate
Cleanup treats symptoms; Query Monitor shows causes. The weakness is that it is diagnostic only and aimed at technical users, so the data it surfaces still needs someone to act on it, and it should be deactivated on production once the investigation ends.
6. Redis Object Cache — Best for Cutting Database Load on Dynamic Pages
Redis Object Cache connects WordPress to a Redis server so repeated query results and transients live in memory instead of MySQL. It suits membership sites, WooCommerce stores, and busy admin dashboards where edge caching cannot help. The standout benefit is that transients stop landing in wp_options entirely. The plugin is free, with more than half a million active installs.
- Persistent object cache backed by Redis
- Moves transients out of the options table
- Dashboard diagnostics and flush controls
- Supports clusters, replication, and Sentinel setups
It attacks the load that page caching leaves behind. The weakness is the prerequisite: the host must provide a Redis server, which many shared plans do not, and a misconfigured connection can cause errors until the drop-in is removed.
7. Super Page Cache — Best Free Alternative to APO
Super Page Cache turns Cloudflare’s free plan into a full HTML cache by managing cache rules and purging the right URLs when content changes. It suits sites that want edge HTML caching without the monthly APO fee. The standout is automatic purge integration on a free Cloudflare plan. The plugin is free.
- Configures Cloudflare to cache HTML pages
- Purges changed URLs automatically on update
- Fallback disk cache when Cloudflare misses
- Bypass controls for logged-in users and dynamic pages
It closes the purge gap in the manual cache-rule approach from Step 15. The weakness is configuration depth: more settings than APO means more room for mistakes, and it should not run alongside APO or another page cache.
8. WP Rocket — Best Premium Performance Suite
WP Rocket bundles page caching, file optimisation, lazy loading, a database cleaner, and a Cloudflare add-on in a plugin that works with sensible defaults on activation. It suits non-technical owners who want one paid tool to handle most of this tutorial. The standout is how much it achieves with almost no configuration. A single-site licence costs $59.95 per year, Plus covers three sites at $119.95, and Multi covers fifty at $299.95.
- Page caching and cache preloading on activation
- Scheduled database cleanup of revisions, transients, and spam
- Delay and defer JavaScript for Core Web Vitals
- Cloudflare add-on for purging and development mode
It is the easiest premium route to good scores. The weakness is price relative to free alternatives, and its database cleaner is basic compared with Advanced Database Cleaner, offering no autoload analysis or orphaned table detection.
9. FlyingPress — Best for Aggressive Core Web Vitals Tuning
FlyingPress focuses on front-end speed: critical CSS, unused CSS removal, lazy rendering, and a page cache designed to work with a CDN. It suits sites whose database is already lean but still fail Core Web Vitals. The standout is how aggressively it removes unused CSS without manual rules. Pricing starts at $59 per year for one site, $109 for three, and $229 for twenty-five, with a 14-day free trial.
- Removes unused CSS and generates critical CSS
- Lazy renders below-the-fold elements
- Page cache with CDN integration
- Built-in database cleanup options
It is strongest where Largest Contentful Paint and render-blocking resources are the problem. The weakness is that its aggressive CSS handling can break layouts on complex themes or page builders, so each change needs visual testing.
10. Perfmatters — Best for Removing Bloat Other Plugins Add
Perfmatters disables WordPress features most sites never use, limits revisions and heartbeat frequency, and unloads plugin scripts on pages that do not need them. It suits owners who already have a cache and want to trim what loads on every request. The standout is the per-page script manager. A personal licence costs $29.95 per year, three sites cost $59.95, and unlimited sites cost $124.95.
- Script manager to unload assets per page or post type
- Toggles for emojis, embeds, XML-RPC, and heartbeat
- Revision limits and autosave interval controls
- Local analytics hosting and preload settings
It complements a caching plugin rather than replacing one, which makes it the lesser-known pick most competing guides skip. The weakness is that it has no page cache and no database cleanup beyond revision limits, so it only makes sense alongside other tools.
11. WP-CLI — Best for Scripted, Repeatable Maintenance
WP-CLI is the official command-line interface for WordPress and runs every export, transient purge, and revision delete in this tutorial without a browser. It suits developers and anyone with SSH access who wants cleanup on a cron schedule. The standout is repeatability: one shell script can back up, clean, and optimise on a timer. It is free and open source.
- Database export, import, search, and optimise commands
- Expired transient deletion in a single command
- Bulk post and revision management
- Works with cron for unattended maintenance
No plugin matches it for speed on large databases because nothing times out. The weakness is access: shared hosts without SSH cannot use it, and a mistyped command runs immediately with no confirmation dialog.
Pricing Comparison for WordPress Optimization Tools
The cheapest complete stack costs nothing. WP-Sweep, Query Monitor, Redis Object Cache where the host provides Redis, Super Page Cache, and WP-CLI together cover measurement, cleanup, object caching, and edge HTML caching on the Cloudflare Free plan. Advanced Database Cleaner’s free tier and WP-Optimize’s free core add scheduling at no cost.
The best value in the middle is Cloudflare APO at $5 per month, which replaces the most fragile part of the free stack, HTML cache purging, with a managed service. Pairing it with Perfmatters at $29.95 per year gives edge caching plus request-level bloat control for well under $100 annually. WP-Optimize Premium at $49 per year is the sensible upgrade for owners who want scheduled cleanup without touching SQL.
The premium tier buys convenience rather than capability. WP Rocket at $59.95 per year for one site and FlyingPress at $59 per year both deliver near-automatic front-end optimisation, while Cloudflare Pro at $20 per month billed annually adds APO, image optimisation, and a stronger WAF. Agencies should compare multi-site tiers: WP Rocket Multi at $299.95 for fifty sites against FlyingPress Business at $229 for twenty-five.
How to Choose the Right WordPress Database Cleanup and Cloudflare Stack
Start with access. Sites with SSH should lean on WP-CLI for cleanup because it is fast, scriptable, and free, and add Query Monitor to verify results. Sites limited to a hosting panel are better served by WP-Optimize or WP-Sweep, which run the same operations from the dashboard.
Next, look at the kind of bloat measured in Part 1. Heavy autoloaded options point to Advanced Database Cleaner, since its ownership detection is the only practical way to trace old plugin leftovers. Heavy analytics and view-counter tables point to the manual SQL in Part 2 plus retention settings in the originating plugins.
Then consider how dynamic the site is. Blogs and magazines benefit most from edge HTML caching, so Cloudflare APO or Super Page Cache delivers the biggest win. Stores, forums, and membership sites serve many uncacheable pages, which makes Redis Object Cache the higher-impact addition.
Budget and team skill come next. A non-technical owner with a modest budget will get further with WP Rocket’s defaults than with a hand-tuned free stack that nobody maintains. A developer comfortable with Cloudflare rules can match or beat it for free.
Finally, avoid stacking overlapping page caches. APO, Super Page Cache, WP Rocket’s page cache, FlyingPress’s page cache, and WP-Optimize’s cache all do the same core job. Choose exactly one, then add non-overlapping tools like Perfmatters and Redis around it.
Current Market Prices and Deals
Several of these tools reward annual billing. Cloudflare Pro drops from $25 per month billed monthly to $20 per month billed annually, and APO is bundled at no extra charge on any paid plan. FlyingPress offers a 14-day free trial on every tier, which is long enough to measure Core Web Vitals before and after. WP-Optimize, Advanced Database Cleaner, WP-Sweep, Query Monitor, Redis Object Cache, and Super Page Cache all have fully functional free versions on WordPress.org, so every part of this tutorial can be tested before any money is spent.
WordPress Database Cleanup and Cloudflare FAQ
Is it safe to clean up a WordPress database?
Yes, provided a full database backup is taken first and cleanup targets known waste such as expired transients, old revisions, spam, and orphaned metadata. The risk comes from deleting options or tables that an active plugin still uses, so anything uncertain should be left alone or tested on a staging copy.
How do I clean up my WordPress database without a plugin?
Use phpMyAdmin’s SQL tab or WP-CLI over SSH. WP-CLI can export a backup, delete expired transients, and remove revisions with single commands, while SQL queries can remove orphaned post meta and trim analytics tables. Finish by running OPTIMIZE TABLE on the largest tables to rebuild them and release freed space.
Does Cloudflare cache HTML pages by default?
No. Cloudflare caches static files such as images, CSS, and JavaScript by file extension, but HTML is not cached unless a cache rule makes it eligible or Automatic Platform Optimization is enabled. Without one of those, every page request still reaches the WordPress server even when the site is proxied through Cloudflare.
Is Cloudflare APO worth it for WordPress?
For most content sites on the Free plan, yes. At $5 per month it caches full pages at the edge and purges them automatically when posts change, which is the hardest part to replicate for free. Sites already on Cloudflare Pro get it included, while stores with mostly dynamic pages see smaller gains.
Why doesn’t my database shrink after OPTIMIZE TABLE?
The server most likely stores InnoDB tables in a shared system tablespace rather than one file per table. In that setup, freed space is reused for new rows but never returned to the disk, so reported size stays flat. Query performance still improves because indexes and data pages are rebuilt without fragmentation.
How often should a WordPress database be optimized?
Every one to three months suits most sites. Busy stores, forums, and sites running analytics or logging plugins benefit from monthly cleanup, while small brochure sites can stretch to quarterly. Scheduling the job in WP-Optimize, Advanced Database Cleaner, or a WP-CLI cron script removes the need to remember it.
Will Cloudflare block Googlebot?
It can if Bot Fight Mode, strict security levels, or broad custom rules challenge crawler traffic. A skip rule placed first that matches verified bots prevents this. On the Free plan, Bot Fight Mode itself cannot be bypassed by custom rules, so it should stay off on sites that depend on organic search.
Pro Tips for Faster WordPress and Cloudflare Performance
Check the autoload total again a week after cleanup. Some plugins recreate large autoloaded options on their next scheduled task, and catching that early reveals which plugin needs its own setting changed rather than repeated manual deletion.
Run OPTIMIZE TABLE during the lowest-traffic hour. The rebuild briefly locks the table on older MySQL and MariaDB versions, and on a large analytics table that pause can be long enough for visitors to notice slow saves or failed form submissions.
Look at Cloudflare’s cache analytics, not just PageSpeed scores. The percentage of requests served from cache shows whether the rules are working; a low ratio on a blog usually means a query string, cookie, or header is fragmenting the cache key.
Add the site’s own uptime monitor to the verified bot rule only if it appears in Cloudflare’s verified list. Unverified monitors should be allowed by their published IP ranges instead, since user agent matching lets scrapers slip through the same gap.
Replace WordPress’s built-in pseudo-cron with a real server cron job on sites with light traffic. Scheduled cleanups from plugins depend on WP-Cron, which only fires when someone visits, so heavily cached sites can go weeks without their maintenance actually running.
Keep a small SQL file of the exact cleanup queries used, with the real table prefix already filled in. Quarterly maintenance then takes minutes, and the same file doubles as documentation for anyone else who looks after the site.
Final Thoughts on WordPress Database Cleanup and Cloudflare Optimization
The order is what makes this work. Back up, measure, clean the specific tables that are bloated, and rebuild them; then lock in the gains with revision limits and plugin retention settings so the same rows do not return. On the Cloudflare side, the verified bots skip rule protects crawl access, the bypass rule protects logged-in users, and static asset and HTML caching take most traffic off the origin entirely.
For most sites the strongest low-cost combination is WP-CLI or WP-Sweep for cleanup, Advanced Database Cleaner when autoload is the problem, and Cloudflare APO for $5 per month to cache HTML at the edge. Owners who prefer a single paid plugin will be well served by WP Rocket, while developers chasing Core Web Vitals should trial FlyingPress. Whichever stack is chosen, repeat the measurement query every quarter and let the numbers decide when the next cleanup is due.
Loading comments…