⏲️ Estimated reading time: 3 min
How to Clear WordPress Cache Programmatically Using PHP
Clearing your WordPress cache can help improve site performance and fix issues related to cached content. While many caching plugins offer built-in options to clear cache, you can also do it programmatically with a simple PHP script. In this guide, we’ll walk you through setting up a custom cache-clearing script for WordPress.
Step 1: Create a PHP File
- Open a text editor (such as Notepad++, VS Code, or Sublime Text).
- Create a new file and name it
clear-cache.php
. - Copy and paste the following code into the file:
<?php
define('WP_USE_THEMES', false);
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
// Define allowed IP addresses to access this script
$allowed_ips = ['94.224.18.73']; // Replace with your actual IP address
if (!in_array($_SERVER['REMOTE_ADDR'], $allowed_ips)) {
die('Access denied.');
}
// Clear cache if the function exists
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
echo "Cache cleared successfully.\n";
} else {
echo "Cache function not available.\n";
}
?>
Step 2: Upload the File to Your Server
- Use an FTP client (such as FileZilla) or your hosting’s File Manager.
- Navigate to your WordPress root directory (usually
public_html
). - Upload the
clear-cache.php
file to the root directory.
Step 3: Secure the Script
To enhance security, only allow specific IP addresses to access this script:
- Replace
'94.224.18.73'
with your own IP address. - You can check your IP by visiting What Is My IP.
- If you want to allow multiple IPs, add them as an array:
$allowed_ips = ['94.224.18.73', '192.168.1.1'];
Step 4: Run the WordPress Cache Script
To manually clear the cache, open your browser and visit:
https://yourdomain.com/clear-cache.php
If successful, you’ll see the message: “Cache cleared successfully.”

Step 5: Automate WordPress Cache Clearing (Optional)
If you want to automate cache clearing, you can set up a cron job:
- Log in to your cPanel.
- Navigate to Cron Jobs.
- Add a new cron job with the following command:
wget -q -O - https://yourdomain.com/clear-cache.php >/dev/null 2>&1
- Set the cron schedule (e.g., every hour, daily, etc.).
Conclusion
By following these steps, you can clear your WordPress cache programmatically and ensure your website runs smoothly. If you’re using caching plugins like WP Rocket, W3 Total Cache, or LiteSpeed Cache, consider using their built-in cache-clearing functions.
Would you like to see more WordPress performance optimization tips? Let us know in the comments!
Only logged-in users can submit reports.
Discover more from HelpZone
Subscribe to get the latest posts sent to your email.