What would be a PHP command to erase all posts from category X from the last month?

The first step is setting up the cron job.

The second part requires querying the database for a specific post type where the entry is older than 1 week. We can do this with get_posts() and specifying the category argument and the date_query argument.

//* If the scheduled event got removed from the cron schedule, re-add it
if( ! wp_next_scheduled( 'wpse_263953_remove_old_entries' ) ) {
  wp_schedule_event( time(), 'daily', 'wpse_263953_remove_old_entries' );
}

//* Add action to hook fired by cron event
add_action( 'wpse_263953_remove_old_entries', 'wpse_263953_remove_old_entries' );
function wpse_263953_remove_old_entries() {
  //* Get all posts older than 7 days...
  $posts = get_posts( [
    'numberposts' => -1,
    //* Use `cat` to query the category ID
    //* 'cat' => 'wpse_263953_category_id',
    //* Use `category_name` to query the category slug
    'category_name' => 'wpse_263953_category',
    'date_query' => [
      'after' => date( "Y-m-d H:i:s", strtotime( '-7 days', current_time( 'timestamp' ) ) ),
      //* For posts older than a month, use '-1 months' in strtotime()
    ],
  ]);
  //* ...and delete them
  foreach( $posts as $post ) {
    wp_delete_post( $post->ID );
  }
}

Leave a Comment