Skip to content

Instantly share code, notes, and snippets.

@davideleuterius
Created September 26, 2017 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davideleuterius/397c39db2667f92539e752a1a9d58899 to your computer and use it in GitHub Desktop.
Save davideleuterius/397c39db2667f92539e752a1a9d58899 to your computer and use it in GitHub Desktop.
auto expiring WordPress posts by custom timestamp (unix)
define( 'EV_POST_TYPE', 'event' );
define( 'EV_DATE_FIELD', 'event_start_date' );
define( 'EV_TIMESTAMP', 'event_timestamp' );
// save start date as unix timestamp
function custom_timestamp ( $post_id ) {
$ev_post_type = 'event';
$ev_date_field = 'event_start_date';
$ev_timestamp = 'event_timestamp';
if ( get_post_type( $post_id ) == $ev_post_type ) :
$the_date = get_post_meta($post_id, $ev_date_field, true);
if( $the_date ) :
$timestamp = strtotime( $the_date );
update_post_meta( $post_id, $ev_timestamp, $timestamp );
endif;
endif;
}
add_action( 'save_post', 'custom_timestamp', 100, 2);
// SCHEDULE DAILY OLD EVENT REMOVAL RUN -----------------------
function remove_expired_events() {
if ( ! wp_next_scheduled( 'delete_expired_events' ) ) :
wp_schedule_event( time(), 'twicedaily', 'delete_expired_events');
endif;
}
add_action( 'wp', 'delete_expired_events' );
// REMOVE EVENTS OLDER THAN TODAY -----------------------------
function delete_expired_events() {
$today = time() + 86400; // add one day to keep from deleting today's events
$args = array(
'post_type' => $ev_post_type,
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => $ev_timestamp,
'value' => $today,
'compare' => '<',
)
)
);
$expired = new WP_Query( $args );
// Cycle through each Post ID
if ( $expired->have_posts() ) :
while ( $expired->have_posts() ) :
$expired->the_post();
wp_delete_post( get_the_ID() );
endwhile;
endif;
wp_reset_postdata();
}
add_action( 'remove_expired_events', 'expired_event_delete' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment