第一步是设置cron作业。
第二部分需要在数据库中查询条目超过1周的特定帖子类型。我们可以使用get\\u posts()并指定category参数和date\\u query参数来实现这一点。
//* 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 );
}
}