How to auto-delete "old" structure field content

I’m using the structure field to create some kind of calender on one of my sites. If the date of the (structure field) post is over, the post is no longer displayed in the frontend. So far so good.

Now my question: Is there a way to auto delete (structure field) posts if their date is over? I know I can do this by hand but … I’m lazy. :wink:

You could either use a hook that runs some code when the page is updated. Or you could use a cron job that triggers a script at given intervals. You could also manually trigger a cleanup via a route or tie this to a button.

Ok, I already had the idea with the hooks, too. Then I wasn’t wrong with that. Nice. But what I ask myself is the following: how can I actually delete older (structure field) posts?

With this function you can add items to a structure field:

  function addToStructure($page, $field, $data = array()){
      $fieldData = page($page)->$field()->yaml();
      $fieldData[] = $data;
      $fieldData = yaml::encode($fieldData);
      try {
        page($page)->update(array($field => $fieldData));
        return true;
      } catch(Exception $e) {
        return $e->getMessage();
      }
    }

You can adapt this to first get the data, then filter by date and remove those items from the array, then update the page with the cleaned up array.

1 Like

Whoop, whoop! Thank you! You’re too fast for me… unbelievable.