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



我有一个WordPress网站,有1000条帖子。我想将所有超过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. 您可以搜索具有日期条件的帖子。这样你就不需要单独检查帖子的年龄了。有了成千上万的帖子,这大大节省了时间。
    $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调试工具。它帮助很大。

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

最新更新