Heiko Mamerow

Web development with WordPress

ChatGPT first try and Bingo!

Its very impressed how easy it is to generate code with ChatGPT. Today i signed up for an ChatGPT account and one of my first questions was:

Write me a WordPress plugin make a database backup every day.

This is what ChatGPT answers me immediately:

Sure, here is a simple WordPress plugin that will create a backup of your WordPress database every day:

  1. Create a new file in your WordPress plugins directory, named something like “database-backup-daily.php”.
  2. Paste the following code into the file:
<?php
/*
Plugin Name: Daily Database Backup
Description: Automatically creates a backup of your WordPress database every day.
Version: 1.0
Author: Your Name
*/

// Hook the backup function to run every day at midnight
add_action('daily_database_backup', 'backup_database');
function backup_database() {
  // Set the filename of the backup file to include the current date
  $backup_file = 'database-backup-' . date('Y-m-d') . '.sql';

  // Create the backup file and save it to the wp-content directory
  system('mysqldump -h [database host] -u [database user] -p[database password] [database name] > ' . WP_CONTENT_DIR . '/' . $backup_file);
}

// Schedule the backup to run every day at midnight
wp_schedule_event(time(), 'daily', 'daily_database_backup');
  1. Replace the following placeholders in the code with your own database information:
    • [database host]: the hostname of your database server
    • [database user]: the username for your database
    • [database password]: the password for your database
    • [database name]: the name of your WordPress database
  2. Save the file and activate the plugin in your WordPress admin dashboard.

That’s it! The plugin will now create a backup of your WordPress database every day at midnight, and save it to the wp-content directory with a filename that includes the current date. You can modify this code to include additional features, such as sending the backup file to an external server or compressing the backup file, depending on your needs.

Not bad! Of course this code is not “best practice” but it shows the ChatGPT has understanding the pattern of WordPress coding very well.

Later i “tweaked” ChatGPT and ask a) to compress the file b) to not allow access from the internet to the backups c) to use WP-CLI and lastly d) use an core hook instead the custom hook. All changes were done promptly and even explained and commented on.

Seems that i will work from now on with ChatGPT very close… 😉


Leave a Reply

Your email address will not be published. Required fields are marked *