Reputation: 83
I am trying to set up a cron job to delete rows older than 48 hours. I've never done this before and decided to try and make a WP scheduled task. Below is my code in my functions.php
file. I am assuming my delete line/query is wrong. Any help would be appreciated; or if there is an easier way I am open to that too. Thanks.
add_action('init','es4u_delete_old_videos');
add_action('es4u_delete_video','es4u_delete_video_func');
function es4u_delete_video_func() {
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
DELETE * FROM awdwp_webinar_orders WHERE start_time < DATEADD(HOUR,-48,GETDATE());
}
function es4u_delete_old_videos(){
if(!wp_next_scheduled('es4u_delete_video')) {
wp_schedule_event (time(), 'hourly', 'es4u_delete_video');
}
}
EDIT: This is what I have now, but tables still aren't deleting. Any idea?
add_action('init','es4u_delete_old_videos');
add_action('es4u_delete_video','es4u_delete_video_func');
function es4u_delete_video_func() {
global $wpdb;
$sql = 'DELETE * FROM awdwp_webinar_orders WHERE start_time < DATEADD(HOUR,-48,GETDATE());';
$wpdb->query( $sql );
}
function es4u_delete_old_videos(){
if(!wp_next_scheduled('es4u_delete_video')) {
wp_schedule_event (time(), 'hourly', 'es4u_delete_video');
}
}
Upvotes: 4
Views: 1252
Reputation: 12524
Instead of using mysqli
functions you can use the built in WordPress class wpdb to do some of the work for you. WordPress creates a global $wpdb
object that you can use.
function es4u_delete_video_func() {
global $wpdb;
$sql = 'DELETE FROM awdwp_webinar_orders WHERE start_time < DATE_ADD( NOW(), INTERVAL -48 HOUR )';
$wpdb->query( $sql );
}
Upvotes: 2