Question

Ok, here goes: ACF has date fields which can be applied to posts, pages, etc. I'm using this to create very basic events, using posts, not pages. I only ever need to use posts for events. With this in mind, here is my question:

I want to know whether it is possible to delete posts with PHP (within the post template), that will (while it loops through the posts), delete the post if the ACF date field for that post is older than the current date.

This seems like something that should have been solved or sought after by now, but I'm not getting great Google results for this. So I'm guessing this may involve cron jobs or some deeper PHP/back-end mastery?

Typically what I'd be doing is the following:

<?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.

    }
}

?>

I do not just want to filter out old events, I want them gone, deleted (keep the DB light).

Ideally I'd prefer not to have to delete old events manually.

Was it helpful?

Solution

You could use wp_delete_post() to remove posts whose start_date is too old:

// 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>';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top