I want to delete all posts of a specific post type (in this case "vfb_entry") that are older than 60 days. The cron job should run once a day.
I have the following code but it's not working if I trigger the cron job. However, running only the query in phpMyAdmin returns the correct result. So there must be an issue with the fuction itself.
Can anyone please help?
// Cron Job to Delete VFB Entries older than 60 days
if(!wp_next_scheduled( 'remove_old_vfb_entries')){
wp_schedule_event(time(), 'daily', 'remove_old_vfb_entries');
}
add_action('remove_old_vfb_entries', 'myd_remove_old_vfb_entries');
// Build the function
function myd_remove_old_vfb_entries(){
global $wpdb;
// Set max post date and post_type name
$date = date("Y-m-d H:i:s", strtotime('-60 days'));
$post_type = 'vfb_entry';
// Build the query
// Only select VFB Entries from LFG or LFM Form
$query = "
SELECT $wpdb->posts.ID FROM $wpdb->posts
WHERE post_type = '$post_type'
AND post_status = 'publish'
AND post_date < '$date'
AND ($wpdb->posts.ID IN (SELECT entry_id FROM wp_postmeta_lfg4 WHERE post_id IS NOT NULL) OR $wpdb->posts.ID IN (SELECT entry_id FROM wp_postmeta_lfm3 WHERE post_id IS NOT NULL))
ORDER BY post_modified DESC
";
$results = $wpdb->get_results($query);
foreach($results as $post){
// Let the WordPress API clean up the entire post trails
wp_delete_post( $post->ID, true);
}
}
Edit: Solution without querying my views, just using wp_posts and wp_postmeta and an INNER JOIN below.
wp_cron()
job fires at all? Have you checked the server logs? Do you have debugging enabled (logged to a file would be best in this case)? Why are you not usingWP_Query
? There is no reason at all I can see to order that result set. That part is a waste of resources.