You have to create a schedule event.
It is a best practice to assign this schedule event to the activation of the plugin, and it should be cleared when the plugin is deactivated.
/**
* Plugin activation
* - create schedule event
*/
function enlsbv7_activation() {
if ( ! wp_next_scheduled( 'enlsbv7_event' ) ) {
wp_schedule_event( time(), 'daily', 'enlsbv7_event' );
}
}
register_activation_hook( __FILE__, 'enlsbv7_activation' );
/**
* Plugin deactivation
* - clear schedule event
*/
function enlsbv7_deactivation() {
wp_clear_scheduled_hook( 'enlsbv7_event' );
}
register_deactivation_hook( __FILE__, 'enlsbv7_deactivation' );
/**
* Delete old pending comments
*/
function enlsbv7_event_delete_old_pending_comments() {
$args = array(
'date_query' => array(
'before' => '3 days ago',
),
'posts_per_page' => - 1,
'status' => 'hold',
'fields' => 'ids',
'no_found_rows' => true,
);
$comment_ids = get_comments( $args );
if ( ! empty( $comment_ids ) ) {
foreach ( $comment_ids as $comment_id ) {
wp_delete_comment( $comment_id, true );
}
}
}
add_action( 'enlsbv7_event', 'enlsbv7_event_delete_old_pending_comments' );
This will delete all pending comments older than 3 days. The schedule event runs daily.