wp_delete_auto_drafts()
云策文档标注
概述
wp_delete_auto_drafts() 函数用于删除超过7天的自动草稿文章。它通过数据库查询和 wp_delete_post() 强制删除来实现清理功能。
关键要点
- 函数自动删除状态为 'auto-draft' 且创建时间超过7天的文章
- 使用 wpdb::get_col() 查询符合条件的文章ID
- 通过 wp_delete_post( $delete, true ) 强制删除文章,不进入回收站
- 该函数自 WordPress 3.4.0 版本引入
代码示例
function wp_delete_autodraft() {
global $wpdb;
// Delete auto-drafts.
$old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft'" );
foreach ( (array) $old_posts as $delete ) {
// Force delete.
wp_delete_post( $delete, true );
}
}
add_action( 'init', 'wp_delete_autodraft' );注意事项
用户贡献的笔记提供了一个自定义函数示例,可以立即删除所有自动草稿,无需等待7天,但需谨慎使用以避免意外数据丢失。
原文内容
Deletes auto-drafts for new posts that are > 7 days old.
Source
function wp_delete_auto_drafts() {
global $wpdb;
// Cleanup old auto-drafts more than 7 days old.
$old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
foreach ( (array) $old_posts as $delete ) {
// Force delete.
wp_delete_post( $delete, true );
}
}
Changelog
| Version | Description |
|---|---|
| 3.4.0 | Introduced. |
Skip to note 2 content
petruciucur
Delete now without waiting 7 days
function wp_delete_autodraft() { global $wpdb; // Delete auto-drafts. $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft'" ); foreach ( (array) $old_posts as $delete ) { // Force delete. wp_delete_post( $delete, true ); } } add_action( 'init', 'wp_delete_autodraft' );