title: WordPress: Delete posts by using the date of a custom field
body: <p>I'm using a Custom Post Type to show events on my site.
  The events have two custom fields for the start and the end date. The dates are stored in the following format: YYYY-MM-DD.</p>
  
  <p>I'm using the field to sort the events in the frontend where I start with the next event based on the current date.</p>
  
  <p>After this date, the events are not showing in the frontend anymore because they lie in the past.</p>
  
  <p>Now I want to delete the events after the end date.
  Is there any way to do this?</p>
  
  <p>I've found a nice solution from @pieter-goosen to delete posts after a number of days: <a href="https://wordpress.stackexchange.com/questions/209046/delete-expired-posts-after-a-number-of-days-after-they-expired">https://wordpress.stackexchange.com/questions/209046/delete-expired-posts-after-a-number-of-days-after-they-expired</a></p>
  
  <p>But I don't know how to use this function with a meta field.</p>
  
  <p>Any ideas/hints?</p>
  
  <p>My code:</p>
  
  <pre><code>function expirePastEvents() {
  
      $current_date_query = date ('Y-m-d');
  
      $postType = 'event'; // Change this to your post type name.
      $metaKeyName = 'gid_22'; // Change this to your meta key name for end date.
      $skipTrash = false; // Whether or not to skip the trash.
  
      $posts = new WP_Query([
          'post_type' =&gt; $postType,
          'fields' =&gt; 'ids',
          'post_status' =&gt; 'publish',
          'meta_query' =&gt; [
              [
                  'key' =&gt; $metaKeyName,
                  //'value' =&gt; current_time('timestamp'),
                  'value' =&gt; $current_date_query,
                  'compare' =&gt; '&lt;='
              ]
          ]
      ]);
  
      foreach ($posts-&gt;posts as $post) {
          wp_delete_post($post-&gt;ID, $skipTrash);
      }
  }
  
  
  
  // expired_post_delete hook fires when the Cron is executed
  add_action( 'expired_post_delete', 'expirePastEvents' );
  
  
  // Add function to register event to wp
  add_action( 'wp', 'register_daily_events_delete_event');
  function register_daily_events_delete_event() {
      // Make sure this event hasn't been scheduled
      if( !wp_next_scheduled( 'expired_post_delete' ) ) {
          // Schedule the event
          wp_schedule_event( time(), 'hourly', 'expired_post_delete' );
      }
  }
  </code></pre>