I'm using the following function to trash a custom post type for events. After an event took place, I delete the trash manually.
I found out, that the posts are still published after they should be deleted. The Version in the trash seems to be a new copy (with a new ID) of the original post?
Is there anything in the function which may produce such an error?
Here is my script:
<?php
function get_delete_old_events() {
$past_query = date('Y-m-d', strtotime('-1 day'));
// WP_Query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => array( 'event' ), //post type
'posts_per_page' => '-1',//fetch all posts,
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'gid_22',
'value' => $past_query,
'compare' => '<='
)
)
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// do something
$headers[] = 'From: Mail <mail@example.com>';
$postid = get_the_ID();
$post = get_post($postid);
$author = get_userdata($post->post_author);
$subject = "subject....: ".$post->post_title."";
$message = "..."
;
wp_mail($author->user_email, $subject, $message, $headers);
wp_trash_post( $id );
// Also tried with this:
// wp_trash_post( $postid );
}
} else {
// no posts found
return false;
}
// Restore original Post Data
wp_reset_postdata();
}
// expired_post_delete hook fires when the Cron is executed
add_action( 'old_event_delete', 'get_delete_old_events' );
// Add function to register event to wp
add_action( 'wp', 'register_daily_events_delete_event');
function register_daily_events_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'old_event_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'hourly', 'old_event_delete' );
}
}
?>
I found my mistake... I'm setting the ID of the post as $postid
and using $id
instead...
If you click the trash link then by default Wordpress will keep it for 30 days before permanently deleting it.
wp_trash_post
moves an item to the trash if the 30 days havent passed and deletes it if they have, so it's working as I would expect it.
If you want to permanently delete a file straight away use wp_delete_post($post_id, true);