You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现WordPress自定义文章类型的自动删除?

自定义文章类型自动删除方案

一、EMPTY_TRASH_DAYS对自定义文章类型的适用性

默认情况下,EMPTY_TRASH_DAYS是全局配置项,仅对支持回收站功能的自定义文章类型生效。

如果你的自定义文章类型在注册时,通过supports参数声明了trash支持(例如'supports' => ['title', 'editor', 'trash']),那么这个常量会自动清理该类型下回收站中超过指定天数的内容;如果没开启回收站支持,这个常量就不会对它产生作用。

二、自定义定时删除的实现方法

如果需要更灵活的规则(比如跳过回收站直接删除、自定义执行周期、针对特定条件的内容),可以通过WordPress的Cron定时任务实现:

1. 注册定时任务

先添加一个定时事件,指定执行频率(以下示例为每日执行):

// 注册定时清理事件
function register_custom_post_cleanup_cron() {
    if ( ! wp_next_scheduled( 'custom_post_cleanup_event' ) ) {
        // 可选周期:hourly、twicedaily、daily、weekly,也可自定义
        wp_schedule_event( time(), 'daily', 'custom_post_cleanup_event' );
    }
}
add_action( 'wp', 'register_custom_post_cleanup_cron' );

2. 编写删除逻辑回调

根据需求编写具体的删除代码,以下提供两种常见场景:

// 自定义文章类型清理逻辑
function custom_post_cleanup_function() {
    // 替换为你的自定义文章类型slug
    $target_post_type = 'your_custom_post_type';

    // 场景1:清理回收站中超过10天的内容
    $trash_posts = get_posts( array(
        'post_type'      => $target_post_type,
        'post_status'    => 'trash',
        'posts_per_page' => -1,
        'date_query'     => array(
            array(
                'before'     => '10 days ago',
                'inclusive'  => true,
            ),
        ),
    ) );

    foreach ( $trash_posts as $post ) {
        wp_delete_post( $post->ID, true ); // true表示彻底删除,不保留到回收站
    }

    // 场景2:直接删除发布超过7天的公开文章(无需进回收站)
    /*
    $expired_posts = get_posts( array(
        'post_type'      => $target_post_type,
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'date_query'     => array(
            array(
                'before'     => '7 days ago',
                'inclusive'  => true,
            ),
        ),
    ) );

    foreach ( $expired_posts as $post ) {
        wp_delete_post( $post->ID, true );
    }
    */
}
add_action( 'custom_post_cleanup_event', 'custom_post_cleanup_function' );

3. 注意事项

  • 确保自定义文章类型注册时设置了正确的权限(capability_type),后台执行Cron任务的用户拥有删除该类型内容的权限。
  • 若需要自定义执行周期(比如每3天一次),需先通过add_filter('cron_schedules', ...)注册新的时间间隔。
  • 测试时可临时替换wp_schedule_event为wp_schedule_single_event( time(), 'custom_post_cleanup_event' ),立即触发一次清理验证逻辑。

内容的提问来源于stack exchange,提问作者user19430201

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:05:23