如果ACF日期字段比当前日期早,自动删除帖子


Wordpress ACF - Auto delete posts if ACF date field is older than current date

好的,是这样的:ACF有日期字段,可以应用于帖子、页面等。我用它来创建非常基本的事件,使用帖子,而不是页面。我只需要在事件中使用帖子。考虑到这一点,我的问题是:

我想知道是否可以用PHP删除帖子(在帖子模板内),这将(虽然它循环通过帖子),如果该帖子的ACF日期字段比当前日期更老,则删除帖子。

这似乎是现在应该解决或追求的东西,但我没有得到很好的谷歌结果。所以我猜这可能涉及到cron作业或一些更深层次的PHP/后端精通?

通常我要做的是:

<?php 
// get posts
$posts = get_posts(array(
    'post_type'     => 'post',
    'posts_per_page'    => -1,
    'meta_key'      => 'start_date',
    'orderby'       => 'meta_value_num',
    'order'         => 'ASC'
));
if( $posts )
{
    foreach( $posts as $post )
    {
        // CODE to delete post if ACF date is old
        $titleID = get_the_title($ID);
        echo '<h3>' . $titleID . '</h3>';
        // I've removed some of the other stuff like links, 
        // excerpts, etc, to keep this simple.
    }
}

?>

我不只是想过滤掉旧的事件,我希望它们消失,删除(保持DB轻)。

理想情况下,我不希望手动删除旧事件。

您可以使用wp_delete_post()删除start_date太旧的帖子:

// get a timestamp from the time string
$post_date = strtotime($post->start_date);
// check if the start_date is older than 1 week
if (((time() - $post_date) > (7 * 24 * 60 * 60))) {
  // to remove the post directly i.e. not moving it to trash
  // you could set the second argument to true
  wp_delete_post($post->ID);
} else {
  print '<h3>' . $post->post_title . '</h3>';
}