Can anybody help me with a function to delete posts older than one year with postmeta, attachements and files?


  • Could you please elaborate more on what you would like to do? – Greeso Mar 27 '17 at 16:11
  • I want to delete all posts older than in example 365 days with all associated data (meta, attachments, files) – Grandeto Mar 27 '17 at 16:25

I find-out an way, when working on a cron related project.
1. Install and active [WP Crontol plugin][1] 2. Go to Tools->Cron Events. 3. Create new cron job at `Add PHP Cron Event tab. Here, I use PHP code

global $wpdb;
$posts_table = $wpdb->prefix . 'posts';
$term_relationships_table = $wpdb->prefix . 'term_relationships';
$postmeta_table = $wpdb->prefix . 'postmeta';

$sql = "DELETE a, b, c
FROM $posts_table a
LEFT JOIN $term_relationships_table b ON (a.ID = b.object_id)
LEFT JOIN $postmeta_table c ON (a.ID = c.post_id)
WHERE a.post_type = 'post'
AND DATEDIFF( NOW(), a.post_date) > 365

$wpdb->query( $wpdb->prepare($sql) );

now and 12:00:00 in Next Run
Once Hourly in Recurrence

  1. Save this cron event and click on run now.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.