Post Expiry based on custom field [Solution!]
-
I saw some posts asking about this so I thought I would share my solution. (Please note that my initial tests were successful but I have not tested it in a production environment yet. It will go live on my site tonight.)
I am using Advanced Custom Fields to create my custom fields. I have an Event custom post type with a start_date & an end_date. I simply added the following code to my theme’s function.php:
function acf_set_expiry($post_id){ //Check if the post has a start_date value if(get_field('start_date', $post_id)){ //if it does, remove the default expiration action remove_action( 'save_post', 'expirationdate_update_post_meta'); if(get_field('end_date', $post_id)){ $date = get_field('end_date', $post_id); } else{ $date = get_field('start_date', $post_id); } expirationdate_update_post_meta_acf($post_id, $date); } } //modified update_post_meta function function expirationdate_update_post_meta_acf($id, $date) { // don't run the echo if this is an auto save if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return; // don't run the echo if the function is called for saving revision. $posttype = get_post_type($id); if ( $posttype == 'revision' ) { return; } else { //'M j, Y' is the format my ACF date field is outputting - can be differ from each setup! $formatted_date = DateTime::createFromFormat('M j, Y', $date); $month = intval($formatted_date->format('m')); $day = intval($formatted_date->format('d')); $year = intval($formatted_date->format('y')); //I am not using time in my ACF field, so I am setting it manually to the end of the day. $hour = 23; $minute = 59; $opts = array(); $ts = get_gmt_from_date("$year-$month-$day $hour:$minute:0",'U'); // Schedule/Update Expiration $opts['expireType'] = 'draft'; $opts['id'] = $id; _scheduleExpiratorEvent($id,$ts,$opts); } } add_action('acf/save_post', 'acf_set_expiry', 1);
Viewing 6 replies - 1 through 6 (of 6 total)
Viewing 6 replies - 1 through 6 (of 6 total)
- The topic ‘Post Expiry based on custom field [Solution!]’ is closed to new replies.