Post Expiry Based on Custom Field Updated Solution
-
In this year-old thread, slickorange provided a solution for using an Advanced Custom Field to set the expiration date via Post Expirator, but I had a number of problems with the implementation a year later.
It seems as though updates to ACF may have introduced some bugs. For instance, saving a post with the expiration date set would fire the expirator schedule event using the value from before the current save. I also had issues with both the scheduler AND the unscheduler firing, and not being able to unschedule by deleting the field value.
Here’s my updated solution:
function acf_set_expiry($post_id, $post, $update){ if ( empty( $_POST['fields'] ) ) return; // You'll have to check to see what key your field uses in POST. // My field name is 'expiration_date', but in post it is referenced as 'field_566f1db32e0c9' // We have to use the POST data because otherwise we'll be using the value from before the save/update if ( isset( $_POST['fields']['field_566f1db32e0c9'] ) ) { // remove the default expiration action if this field exists remove_action( 'save_post', 'expirationdate_update_post_meta'); } // Check if the post has a expiration_date value if ( !empty( $_POST['fields']['field_566f1db32e0c9'] ) ) { $date = $_POST['fields']['field_566f1db32e0c9']; expirationdate_update_post_meta_acf($post_id, $date); } else { // Unschedule any existing event if the field is blank _unscheduleExpiratorEvent($post_id); } } //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; // 'yymmdd' is the format my ACF date field is outputting, which is an accepted format for the DateTime constuctor. // Check how you're saving your date, and use the appropriate method to get it into a DateTime $formatted_date = new DateTime($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( 'save_post', 'acf_set_expiry', 1, 3 );
- The topic ‘Post Expiry Based on Custom Field Updated Solution’ is closed to new replies.