Reputation: 191
On save_post, I want to add expiring date (now + 30 days) to a post if this meta_key doesn't exist, otherwise do nothing.
I tried with this code in my function.php:
add_action( 'save_post', 'update_date' );
function update_date( $post_id ) {
$expire = date( 'm/d/Y H:i:s', strtotime( '+' . '30' . ' days' ) );
$meta_exist = get_post_meta($post_id, 'expire_date', true);
if ($meta_exist == ''){
add_post_meta( $post_id, 'expire_date', $expire, true );
}
}
But I noted that this way it update always the date, also if it is already defined.
How to add the date only if needed?
Upvotes: 0
Views: 79
Reputation: 5721
Verify post is not a revision, I change your code slighty:
add_action( 'save_post', 'update_date' );
function update_date( $post_id ) {
if (!wp_is_post_revision($post_id)) {
$expire = date( 'm/d/Y H:i:s', strtotime( '+' . '30' . ' days' ) );
$meta_exist = get_post_meta($post_id, 'expire_date', true);
if (!$meta_exist){
add_post_meta( $post_id, 'expire_date', $expire, true );
}
}
}
Upvotes: 1