I am trying to create/update post meta when you create/update a post that is specifically a post type of "offer". However, it does not update the post meta. This code is added in my functions.php file.
add_filter( 'pre_post_update', 'update_voucher_deadline', 10, 2 );
function update_voucher_deadline( $post_id, $data ) {
$evergreen = get_field('offer_evergreen', $post_id);
if ($evergreen == "evergreen-yes") {
$year = date('Y');
$month = date('m');
$currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
$day = date("t", strtotime($currentDate));
$endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";
//global $post; Tried with this uncommented and also didn't work.
if ( ! add_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth)) {
update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
}
}
}
I see you use ACF plugin to create custom field which means you can use
acf/save_post
filter to do this something like this.1. Check if we save post type 'offer'
2. Check if we have custom field 'offer_evergreen' with value 'evergreen-yes'
3. Check if we have custom filed 'offer_voucher_deadline' if yes - update him.
4. If we do not have custom filed 'offer_voucher_deadline' create him and save our data.
First of all
pre_post_update
hook will not fires on create, it will fires immediately before an existing post is updated.You need to use
save_post
hook it will triggered whenever a post or page is created or updatedNote: you can update your function using
$update
param if necessary.