[英]Automatically draft WordPress Posts older than 30 days using CRON
I have a WordPress site with 1000s of posts.我有一个包含 1000 多个帖子的 WordPress 网站。 I'd like to set all posts older than 30 days to
draft
automatically when it reaches the specified date.我想将所有超过 30 天的帖子设置为在到达指定日期时自动
draft
。
Been staring myself blind at the following code - triggering the CRON manually has now effect:一直盯着自己看下面的代码 - 手动触发 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' );
What am I doing wrong?我究竟做错了什么?
add_action( 'wp_footer', 'tgs_draft_posts_handler')
You can then include print_r();
print_r();
debugging code and it will show up on your rendered page: ugly but useful.print_r('about to do get_posts');
print_r('about to do get_posts');
for example. $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' ) ), ) );
And, turn on the WordPress debugging stuff .并且,打开WordPress 调试工具。 It helps a lot.
它有很大帮助。
When it all works, don't forget to remove the print_r() statements (duh, obviously).当一切正常时,不要忘记删除 print_r() 语句(废话,显然)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.