使用 CRON 自动起草超过 30 天的 WordPress 帖子

Automatically draft WordPress Posts older than 30 days using CRON

我有一个包含 1000 多个帖子的 WordPress 网站。我想在到达指定日期时将所有超过 30 天的帖子自动设置为 draft

一直盯着下面的代码看——现在手动触发 CRON 有效:

<?php
/**
 * Function that will draft specific posts on specific conditions
 *
 * @param \WP_Post $_post
 */
function tgs_maybe_draft_the_post( $_post ) {
    

    $publish_date = get_the_date( 'd M Y', $_post->ID);

    // Bail if no publish date set for some reason.
    if ( ! $publish_date ) {
        return;
    }
    
    // Set status to draft if older than 30 days.
    if (strtotime($publish_date) < strtotime('-30 days')) {
        wp_update_post( array(
            'ID'          => $_post->ID,
            'post_status' => 'draft'
        ) );
    }
}

/**
 * Register cron event on init action
 */
function tgs_cron_schedule_draft_posts() {
    $timestamp = wp_next_scheduled( 'tgs_draft_posts' );
    if ( $timestamp == false ) {
        wp_schedule_event( time(), 'hourly', 'tgs_draft_posts' );
    }
}
add_action( 'init', 'tgs_cron_schedule_draft_posts' );

/**
 * Handle deletion of posts periodically.
 * - Loop through the posts and call the tgs_maybe_draft_the_post function.
 */
function tgs_draft_posts_handler() {
    $posts = get_posts( array(
        'posts_per_page' => - 1,
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'suppress_filters' => true,
    ) );
    foreach ( $posts as $_post ) {
        tgs_maybe_draft_the_post( $_post );
    }
}
add_action( 'tgs_draft_posts', 'tgs_draft_posts_handler' );

我做错了什么?

  1. 您可以通过 运行 直接在页面查看期间而不是从 cron 来解决您的逻辑问题(将状态更改为草稿)。尝试使用 wp_footer 操作,类似这样。
    add_action( 'wp_footer', 'tgs_draft_posts_handler')
    
    然后您可以包含 print_r(); 调试代码,它会显示在您呈现的页面上:丑陋但有用。例如,你可以做 print_r('about to do get_posts');
  2. 您可以搜索 date criteria 的帖子。这样你就不需要单独检查帖子的年龄。有成千上万的帖子,这可以节省大量时间。
        $posts = get_posts( array(
         'posts_per_page' => - 1,
         'post_type'      => 'post',
         'post_status'    => 'publish',
         'suppress_filters' => true,
         'date_query' => array(
             array(
                'column' => 'post_date_gmt',
                'before' => '30 days ago'
             )
           ),
     ) );
    
  3. 一旦你的基本逻辑起作用,你就可以让它在 cron 下运行。

然后,打开 WordPress debugging stuff。很有帮助。

当一切正常时,不要忘记删除 print_r() 语句(显然是废话)。