Search code examples
phpwordpresspost-meta

Wordpress On Edit Post Page Save, Update Post Meta


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);
        }
    }
}

Solution

  • 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.

    add_filter('acf/save_post', 'update_voucher_deadline', 20);
    function update_voucher_deadline($post_id) {
        if ( get_post_type($post_id) != 'offer' ) //if current post type not equal 'offer' return
            return;
    
             $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";
    
        if ( get_field('offer_evergreen') == 'evergreen-yes' ) {
    
            if ( get_post_meta( $post_id, 'offer_voucher_deadline', true ) ) //If get post meta with key 'offer_voucher_deadline' - update meta
                update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
            else //else if do not have post meta with key 'offer_voucher_deadline' create post meta
                add_post_meta( $post_id, 'offer_voucher_deadline', $endOfMonth);
    
        } else {
            return; //Remove return and add what you want to save, if offer_evergreen not equal to evergreen-yes
        }
    }