I've a function which deletes custom post types after a specific time. In my case after 30 days. The problem is, that the posts are not trashed. Instead WordPress creates a new version of the post with new ID and moves this new version in the trash. The status of the old version is still "published".
I delete posts with wp_trash_post()
. I tried do delete them permanently with wp_delete_post()
. The proble is, that wp_delete_post only works with native post types and not with custom post types.
And there is something strange... The function worked very well for a while and now it's broken?! Is it possible, that there is a bug in the new WordPress version (4.9)?
Here is the code of my function:
<?php
function get_delete_old_jobs() {
// WP_Query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => array( 'post_type' ), //post type
'posts_per_page' => '-1',//fetch all posts,
'date_query' => array(
'before' => date('Y-m-d', strtotime('-30 days'))
)
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$postid = get_the_ID();
$post = get_post($postid);
// do something
// ....
// here I generate an e-mail for the author
wp_mail($author->user_email, $subject, $message, $headers);
wp_trash_post( $id );
// also tried this version
// wp_trash_post( $post_id );
}
} 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_job_delete', 'get_delete_old_jobs' );
// Add function to register event to wp
add_action( 'wp', 'register_daily_jobs_delete_event');
function register_daily_jobs_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'old_job_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'hourly', 'old_job_delete' );
}
}
?>
$postid
and using$id
instead. Seems to work now. Thanks for the hint!!